HTML input pattern validation is not working

Sarthak Batra picture Sarthak Batra · Jan 14, 2016 · Viewed 17.5k times · Source

I am trying to validate my HTML input with the pattern attribute. For some cases it's working, for some cases it's not working, and I am not able to figure out why it is breaking.

Let me share two pieces of code with you. Code 1 is working. Code 2 is not. I wrote Code 1 first and then Code 2. I literally copy-pasted Code 2, yet for some reason beyond my understanding, it is not working. Check it out.

CODE1 (the one that's working)

<input id="clinicProfileNumber" name="clinicProfileNumber" ng-model="clinic.profile.number" type="text" class="user-input" pattern="[0-9]{10}" title="10 digit mobile number">

Code2 (the one that's not working)

<input id="doctorProfileContactnumber" name="doctorProfileContactnumber" ng-model="doctor.profile.contactNumber" type="text" class="user-input" pattern="[0-9]{10}" title="10 digit mobile number">

Let me give you a few other examples of code that is not working:

<input id="doctorProfileEmail"
       name="doctorProfileEmail"
       ng-model="doctor.profile.email"
       pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$"
       required type="text"
       class="user-input"
       title="Please enter a valid email." />

<input id="doctorProfilePassword"
       name="doctorProfilePassword"
       ng-model="doctor.profile.password"
       type="text"
       class="user-input"
       pattern=".{6,}"
       title="Must contain at least 6 or more characters">

</div>

Please check this and let me know what am I doing wrong.

Answer

Shrikant picture Shrikant · Jan 14, 2016

Your code is looking great. Just add it in the form tag, like this

<form action="demo">
    Country code: <input type="text"
                         name="country_code"
                         pattern="[A-Za-z]{6,}"
                         title="Three letter country code">

    <input id="doctorProfileContactnumber"
           name="doctorProfileContactnumber"
           ng-model="doctor.profile.contactNumber"
           type="text"
           class="user-input"
           pattern="[0-9]{10}"
           title="10 digit mobile number">

    <input type="submit">
</form>