Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🛡️ Days 23–27 – Professional JavaScript  ·  दिन 23

दिन 23: असली Validation के लिए Regular Expressions

⏱ 95 min📶 Intermediate → Pro🎯 100% self-study
दिन 23 / 30

✅ आज आप सीखेंगे

  • Regular expression क्या है और इसे कैसे पढ़ें
  • Character classes, quantifiers, anchors
  • Groups, alternation, named groups और flags
  • Patterns के साथ test, match, matchAll, replace
  • असली Indian validations – और regex कब न लें

🏢 असली दुनिया में

Sharma Sweets का B2B wholesale form दुकानों से orders लेता है। इसे दुकान का GSTIN, PIN code और कई formats में mobile number (+91 98290-12345, 09829012345, 98290 12345) चाहिए। if/else और indexOf से यह सैकड़ों lines है; regular expressions से हर एक की एक line – बस पढ़ना आना चाहिए।

Regular expression पढ़ना

JavaScript
const pin = /^[1-9][0-9]{5}$/;     // Indian PIN code
console.log(pin.test('302003'));   // true
console.log(pin.test('012345'));   // false – cannot start with 0
console.log(pin.test('30200'));    // false – only 5 digits
console.log(pin.test('302003a'));  // false – $ means the string must end here
true false false false
^ text की शुरुआत[1-9] 1 से 9 तक एक अंक[0-9]{5} ठीक पाँच अंक$ text का अंत
/^[1-9][0-9]{5}$/ को बाएँ से दाएँ पढ़ें
Tokenकिससे मेलउदाहरण
\d / \Dअंक / अंक नहीं\d{10} = दस अंक
\w / \sअक्षर, अंक या _ / whitespace\s+ = एक या अधिक spaces
[abc] / [^abc]a, b, c में से एक / इनके अलावा[A-Z] एक capital letter
.नई line के अलावा कोई भी characterअसली dot के लिए \.
* + ?0 या अधिक / 1 या अधिक / 0 या 1colou?r
{n} {n,} {n,m}ठीक n / कम से कम n / n से m\d{4,6}
^ $Text की शुरुआत / अंतपूरी value validation
\bWord boundary\bkaju\b
( ) |Group / OR(milk|dry)
(? )Named group(?\d{6})

असली Indian validations

JavaScript
const patterns = {
  mobile: /^(?:\+?91[\s-]?|0)?[6-9]\d{4}[\s-]?\d{5}$/,              // +91 98290-12345, 09829012345 …
  pin:    /^[1-9]\d{5}$/,
  gstin:  /^\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$/,               // 15 chars: state code + PAN + entity + Z + checksum
  pan:    /^[A-Z]{5}\d{4}[A-Z]$/,
  ifsc:   /^[A-Z]{4}0[A-Z0-9]{6}$/,
  vehicle:/^[A-Z]{2}[ -]?\d{1,2}[ -]?[A-Z]{1,3}[ -]?\d{4}$/,           // RJ 14 CX 1234
};
const tests = {
  mobile: ['+91 98290-12345', '09829012345', '9829012345', '5829012345', '98290123'],
  pin: ['302003', '102003', '002003'],
  gstin: ['08ABCDE1234F1Z5', '08ABCDE1234F1X5'],
  pan: ['ABCDE1234F', 'ABCD1234F'],
  ifsc: ['SBIN0001234', 'SBIN1001234'],
  vehicle: ['RJ 14 CX 1234', 'RJ14CX1234', 'R 14 CX 1234'],
};
for (const [name, values] of Object.entries(tests)) {
  console.log(name.padEnd(8), values.map(v => `${v} ${patterns[name].test(v) ? '✅' : '❌'}`).join('  '));
}
mobile +91 98290-12345 ✅ 09829012345 ✅ 9829012345 ✅ 5829012345 ❌ 98290123 ❌ pin 302003 ✅ 102003 ✅ 002003 ❌ gstin 08ABCDE1234F1Z5 ✅ 08ABCDE1234F1X5 ❌ pan ABCDE1234F ✅ ABCD1234F ❌ ifsc SBIN0001234 ✅ SBIN1001234 ❌ vehicle RJ 14 CX 1234 ✅ RJ14CX1234 ✅ R 14 CX 1234 ❌
⚠️ Format ≠ असली

Regex सिर्फ़ आकार जाँचता है। 08ABCDE1234F1Z5 का GSTIN format सही है पर हो सकता है वह मौजूद न हो; mobile number बंद हो सकता है। असली verification के लिए checksum, OTP या server पर सरकारी API चाहिए। PAN या Aadhaar numbers तब तक कभी न रखें जब तक सच में ज़रूरी न हो और सहमति न हो।

पहले साफ़ करें, फिर validate

JavaScript
function normaliseMobile(input) {
  const digits = input.replace(/\D/g, '');          // remove everything that is not a digit
  const ten = digits.replace(/^(91|0)(?=\d{10}$)/, '');   // drop a leading 91 or 0 if 10 digits remain
  return /^[6-9]\d{9}$/.test(ten) ? ten : null;
}
['+91 98290-12345', '(0) 98290 12345', '919829012345', '12345'].forEach(v => console.log(v.padEnd(18), '→', normaliseMobile(v)));

const pretty = n => n.replace(/^(\d{5})(\d{5})$/, '+91 $1 $2');    // $1, $2 = captured groups
console.log(pretty('9829012345'));
+91 98290-12345 → 9829012345 (0) 98290 12345 → 9829012345 919829012345 → 9829012345 12345 → null +91 98290 12345

खोजना, निकालना और बदलना

JavaScript
const sms = 'Order #1042 for ₹1,800 confirmed. Order #1043 for ₹650 pending. Call 98290 12345.';

console.log(/order #\d+/i.test(sms));                      // i = case-insensitive
console.log(sms.match(/#\d+/g));                           // g = all matches
for (const m of sms.matchAll(/#(?<id>\d+) for ₹(?<amount>[\d,]+) (?<status>\w+)/g)) {
  const { id, amount, status } = m.groups;                  // named groups
  console.log(id, Number(amount.replace(/,/g, '')), status);
}
console.log(sms.replace(/\d{5} \d{5}/, '***** *****'));   // mask a phone number
console.log('kaju  katli   box'.replace(/\s+/g, ' '));      // collapse spaces
console.log('Ghewar,Rasmalai; Ladoo | Peda'.split(/\s*[,;|]\s*/));
true [ '#1042', '#1043' ] 1042 1800 confirmed 1043 650 pending Order #1042 for ₹1,800 confirmed. Order #1043 for ₹650 pending. Call ***** *****. kaju katli box [ 'Ghewar', 'Rasmalai', 'Ladoo', 'Peda' ]
Methodलौटाता हैउपयोग
regex.test(str)true / falseValidation
str.match(regex)पहला मेल (g से सभी), या nullValues निकालना
str.matchAll(regex /g)Groups वाले matches का iteratorकई structured values निकालना
str.replace(regex, x)नई stringसाफ़, mask, format; $1 groups दर्शाता है
str.split(regex)Arrayकई separators पर बाँटना
new RegExp(text, "gi")String से बना regexDynamic search (user input escape करें!)

असली task: search शब्द सुरक्षित highlight

HTML + JavaScript
<input id="q" value="ka" placeholder="Search" aria-label="Search">
<ul id="list"></ul>

<script>
const items = ['Kaju Katli', 'Kalakand', 'Malai Ghewar', 'Besan Ladoo', 'Soan Papdi (1+1 offer)'];
const escape = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');      // treat user text literally

function render() {
  const q = document.querySelector('#q').value.trim();
  const list = document.querySelector('#list');
  list.innerHTML = '';
  const re = q ? new RegExp(`(${escape(q)})`, 'gi') : null;
  for (const name of items) {
    if (re && !name.match(re)) continue;
    const li = document.createElement('li');
    if (!re) { li.textContent = name; list.append(li); continue; }
    name.split(re).forEach((part, i) => {               // split keeps captured groups
      const node = i % 2 ? document.createElement('mark') : document.createTextNode(part);
      if (i % 2) node.textContent = part;
      li.append(node);
    });
    list.append(li);
  }
}
document.querySelector('#q').addEventListener('input', render);
render();
</script>
▶  Try “ka”, “1+1”, “(” – escaping prevents regex errors
💡 Regex कब न लें

HTML, JSON या पूरे e-mail RFC नियम regex से parse न करें। DOMParser, JSON.parse और साधारण e-mail जाँच (/^[^\s@]+@[^\s@]+\.[^\s@]+$/) व confirmation e-mail लें। Regex छोटे, commented और tested रखें।

🏅 आज के Job Skills

✔ Classes, quantifiers और anchors से regular expressions पढ़ना-लिखना✔ Indian formats validate: mobile, PIN, GSTIN, IFSC✔ Input साफ़ करना और groups से data निकालना✔ सुरक्षित replace, split और highlight; regex की सीमाएँ जानना

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: isStrongPassword(p) लिखें: 8+ chars, कम से कम एक lower, एक upper, एक अंक और एक symbol – lookaheads (?=…) से।
Solution देखें
JavaScript
const strong = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{8,}$/;
for (const p of ['sweets123', 'Sweets123', 'Sweets@123', 'S@1a']) {
  console.log(p.padEnd(11), strong.test(p) ? 'strong ✅' : 'weak ❌');
}
sweets123 weak ❌ Sweets123 weak ❌ Sweets@123 strong ✅ S@1a weak ❌
Task 2: Bill text से “₹1,800” या “₹650.50” जैसी हर राशि निकालकर उनका total print करें।
Solution देखें
JavaScript
const bill = 'Kaju Katli ₹1,800; Ghewar ₹650.50; Delivery ₹60; Discount -₹100';
const amounts = [...bill.matchAll(/(-?)₹([\d,]+(?:\.\d{1,2})?)/g)]
  .map(m => (m[1] ? -1 : 1) * Number(m[2].replace(/,/g, '')));
console.log(amounts, 'Total:', amounts.reduce((a, b) => a + b, 0));
[ 1800, 650.5, 60, -100 ] Total: 2410.5
Task 3: Indian vehicle numbers का regex लिखें जो lower-case input भी माने (i flag) और पाँच उदाहरणों से जाँचें।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. /^\d{6}$/ किससे मेल खाता है?
Anchors ^ $।
2. g flag का मतलब…
match/replace के साथ।
3. 'a1b2'.replace(/\d/g, '') देता है…
अंक हटे।
4. new RegExp() में user text से पहले…
वरना ( या + तोड़ देते हैं।
5. क्या valid GSTIN format से business का होना पक्का है?
Server पर verify करें।

Interview corner

💼 Interview Corner

Indian mobile number कैसे validate करेंगे?

Non-digits और वैकल्पिक 91/0 prefix हटाकर साफ़ करें, फिर /^[6-9]\d{9}$/ जाँचें। ग़लत input पर दोस्ताना message दिखाएँ, और server पर OTP से मालिकाना जाँचें – सिर्फ़ format जाँच सबूत नहीं।

Greedy और lazy quantifiers क्या हैं?

Greedy quantifiers (*, +, {n,}) जितना हो सके उतना मेल करते हैं; ? जोड़ने (*?, +?) से lazy, जितना कम हो सके – जैसे /<.+?>/ पहले < और आख़िरी > के बीच सब की जगह एक tag से मेल खाता है।

सारांश

  • Regex = classes, quantifiers, anchors और groups का pattern।
  • पूरी value validation के लिए ^ … $; पहले input साफ़ करें।
  • Validate को test, निकालने को matchAll/groups, साफ़ व mask करने को replace।
  • User input escape करें; regex format जाँचता है, सच नहीं।
➡️ आगे

Day 24: higher-order functions, debounce और throttle – search boxes और scroll handlers तेज़ बनाएँ।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

Regex जल्दी कैसे test करें?
regex101.com (JavaScript flavour चुनें) – हर हिस्से की व्याख्या और कई inputs एक साथ test।
क्या regex धीमा हो सकता है?
हाँ – (a+)+ जैसे बुरी तरह nested quantifiers कुछ inputs पर exponential समय ले सकते हैं (ReDoS)। Patterns सरल रखें और input length सीमित करें।
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 24: Higher-Order Functions, Debounce और Throttle आपकी प्रगति: 23 / 30 (77%) · Lesson 24 / 30 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें