Use custom regular expressions to validate form - javascript

I would like to validate the form using my custom data attributes but not sure how this is done. I also want to display the error messages in the data attributes if required.
I am looking for the JavaScript which matches the regex values from the data attributes and matches it against the corresponding input values.
I have the following form..
<form id="loginForm" name="loginForm">
<ul>
<li>
<label for="Username">Username:</label>
<input type="email" data-validation-error="Please enter a username" data-validation-use="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" id="username" name="username" maxlength="254" class="required" />
</li>
<li>
<label for="Password">Password:</label>
<input type="password" data-validation-error="Please enter a password" data-validation-use="^[a-zA-Z]\w{5,12}$" id="password" name="password" value="" maxlength="12" class="required" />
</li>
</ul>
<input type="submit" value="Login" class="button" name="loginBtn" id="loginBtn" />
</form>

If you're developing for modern browsers only, you can use a few nice features for this:
List itemUse input type email for the username field. The browser will take care of the validation.
Use attribute required. The browser won't let the user submit without a value in the field.
Use attribute pattern. The browser won't let the user submit without the value matching the given pattern. Altough, with email type, you could skip the horrible regex matching emails of yours :)
Check out the pattern attribute:
http://www.the-art-of-web.com/html/html5-form-validation/#section_6
Example:
<input type="email" required />
Here you can check out the support for modern form features in the most used browsers:
http://caniuse.com/#feat=forms
There is an ongoing discussion if it should be possible to specify and style the error messages (handled by the browser). As for now, I don't think it's possible to style the validation messages. Maybe it's more user friendly if these messages is equal across all pages?
If you need to support older browsers, you'll have to put javascript event handlers on each field, extract the regex from the data attributes and match it against the value. Keep in mind that client side validation is no substitute for server side validation - it's just for user convenience. Therefore, HTML5 validation could be good enough for those with browsers supporting it - the rest will still have server side validation to rely on, altought the user experience won't be that great.
This example shows how it could be done (I haven't tested this very well :o):
$('form').submit(function(){
var isValid = true;
$(this).find(':input').each(function(){
var regex = new RegExp($(this).attr('data-validation-use'));
if(!regex.exec($(this).val())){
$('.validationError').append($(this).attr('data-validation-error'));
$(this).addClass('invalid');
isValid = false;
}
});
return isValid;
});

jquery validation will be best.
See the demo and code of standard jQuery validation here. jQuery Validation

Related

Can a javascript program read the validation result given by `type="email"` of `input` element?

in HTML, type="email" of input element can validate if an input string has a valid email format.
I would like to write a javascript program which will act differently when an input string to such an input element has or doesn't have a valid email format.
Can a javascript program read the validation result given by type="email" of input element? If not, why?
Or do I have to implement validation of email format in Javascript instead?
Thanks.
You can use the :invalid pseudoselector and querySelectorAll. In the following two email inputs - one with an invalid value set and one with a valid email. Css styling (using the :invalid pseudoselector to indicate which one is which. The console log will query all inputs that are invalid and log them.
The bigger issue may be the validation that is required to pass may be as simple as requiring a "#" symbol - so this is not a very stringent validation.
var test = document.querySelectorAll('input:invalid');
console.log(test);
input:invalid{background: red}
<input type="email" value="blah.com"/>
<input type="email" value="blah#blah.com"/>
It seem you can do something like this
<form id='form' action='post'>
<input id='email' type='email' required/>
<input type='submit' value='Submit'/>
</form>
<script>
console.log( document.getElementById('form').checkValidity() );
console.log( document.getElementById('email').checkValidity() );
</script>

How to use Regular Expressions with a Form using Angular (no jQuery)

I have a simple input field. I want to make sure certain rules are met before submission
The password must:
0. have at least 8 characters
1. have no more than 8 characters
2. have both upper and lower case characters
3. have at least 1 letters
4. have at least 1 digits
5. have one of # # $
6. contain only characters available on a standard English (US) keyboard. List of valid characters
7. not be an old password
My Html Form
<form name="login" action="index_submit" method="get" accept-charset="utf-8">
<ul>
<li><label for="username">Email</label>
<input type="email" name="username" placeholder="username#example.com" required></li>
<li><label for="password">Current Password</label>
<input type="password" name="current_password" placeholder="current password" required></li>
<li><label for="password">New Password</label>
<input type="password" name="new_password" placeholder="new password" required></li>
<li>
<input type="submit" value="Login"></li>
</ul>
</form>
I only want to apply the rules to the "new_password"
Add a checkmark (green) if the rules are successful or red X if they don't meet the criteria.
I am new to Angular but not new to RegEx. I have the Expression
"^(?=.{8}$)(?=.*[A-Z])(?=.*[0-9])(?=.*[,##$])"
It would be nice to know which of the rules it has been violated
You can use ngPattern on the input. More information here.
You can use ng-pattern for Regex. This will not allow you to know which of the rules encoded in your pattern were violated. For that, you may want to use a combination of directives like, ng-minlength, ng-maxlength.
Take a look at: https://docs.angularjs.org/guide/forms
You can also use custom $validators in order to apply specific validation logic to your fields (but like the other posters mentioned, ng-pattern is great for that purpose).
It's working in conjunction with models, when you model changes (= the field value changes), it's checking it against the custom registered $validators (through a directive for instance) and updating the model with the results of the validation.
Here is a working plunkr with your regexp: http://embed.plnkr.co/CdITVLnZOZgAzrqAV4iA/preview
(you can use the code view to check out how it's done)
You can also read the AngularJs documentation about forms, you can do a lot of interesting stuff using directives and models within your forms.
https://docs.angularjs.org/guide/forms

How do you disable input value on web form field / input tag?

How do you disable the autocomplete functionality in the major browsers for a specific input (or form field)?
<input type="text" id="fullname" name="fullname" class="form-control" data-required="true" value="<?php echo $_POST['fullname']?>" >
When I open this form I see the value in this input even if I didn't insert any value.
I think adding autocomplete="off" would get you an error on most browsers, furthermore, autocomplete="off" is an invalid property.
Try to check the Mozilla Developer Documentation instead.
Just use the autocomplete attribute:
<input type="text" autocomplete="off"/>
"This would be useful when a text input is one-off and unique. Like a
CAPTCHA input, one-time use codes, or for when you have built your own
auto-suggest/auto-complete feature and need to turn off the browser
default."
Source : CSS Tricks
You could generate a random string using javasript or php and add it to the end of an input name, maybe even use a delimiter to split it apart from the actual name.
In php, you could use something like the session_id for this and simply echo it to the end of the name.
<input type="text" autocomplete="off" name="example<?php echo "," . session_id()?>">
You can replace the "," with any delimiter of your choice, so long as it isn't alphanumeric. Then when processing the data submitted, you can remove it from the end of the actual name of the input field.
With a field name always being different, your browser cant autocomplete it.
Source: https://stackoverflow.com/a/218453/12251360
Solution 1
<form name="form1" id="form1" method="post"
autocomplete="off" action="http://www.example.com/form.cgi">
This will work in Internet Explorer and Mozilla FireFox, the downside is that it is not XHTML standard.
Solution 2
The solution for Chrome is to add autocomplete="new-password" to the input type password.
Example:
<form name="myForm"" method="post">
<input name="user" type="text" />
<input name="pass" type="password" autocomplete="new-password" />
<input type="submit">
</form>
Chrome always autocomplete the data if it finds a box of type password, just enough to indicate for that box autocomplete = "new-password".
This works well for me.
Note: make sure with F12 that your changes take effect, many times browsers save the page in cache, this gave me a bad impression that it did not work, but the browser did not actually bring the changes.
Solution 3
<input type="text" id="fullname" name="fullname" autocomplete="off" class="form-control" data-required="true" value="<?php echo $_POST['fullname']?>" >
links
Solution 3 Reference : https://stackoverflow.com/a/25496311/6923146
Solution 2 Reference : https://stackoverflow.com/a/40791726/6923146

Is there a way for a form to identify only one required field

For instance in this example;
<form>
<input type="email" name="email" id="useremail" placeholder="Email Address" required> <br>
<input type="tel" name="phone" id="userphone" placeholder="Phone Number" maxlength="10" required> <br>
<input type="submit" id="sidebarformsubmit" value="Submit">
</form>
Is it possible to somehow/somewhere be able to identify that the user has inputed something in EITHER the email or phone number field. So that on submit it doesn't show "this is required".
Reword: Can at least one of the form inputs be mandatory, both is allowed as is one or the other but not none. In the above example, the user needs to have at least one form of communication whether that be phone number or email. They can have both however, but not none.
If so, how would you go about this?
You can easily capture the change events from the inputs and set the required attribute accordingly.
Like this:
var email = document.getElementById('useremail'),
phone = document.getElementById('userphone');
function onchange(){
email[phone.value?'removeAttribute':'setAttribute']('required','required');
phone[email.value?'removeAttribute':'setAttribute']('required','required');
}
email.addEventListener('change',onchange);
phone.addEventListener('change',onchange);
jsfiddle
Is it possible to somehow/somewhere be able to identify that the user has inputed something in EITHER the email or phone number field. So that on submit it doesn't show "this is required".
1) No. If you use HTML5 required on a field then that field is required. There is no way to specify interdependence.
2) Yes. You can use client-side javascript validation, generally hooked to a form submit event to do as-complex-as-you-like validation. Prevent the submit by returning false from the event handler if you don't pass validation.
3) Yes. You can do validation that can be as complex as necessary on the server when you have received the submitted form, and return directly to the form if something is wrong.
3b) You Must do validation on the server, even if you have great client-side javascript validation, otherwise I will buy things from your site for one penny. You must not trust the client.

Disable Safari 7.0.2 keychain password save

How can I disable safari from saving a user/pass from a form using html or javascript?
I've had this issue that came up with safari 7.0.2 where you can save a user/pass to a keychain and when you goto that same form it automatically overrides those fields? Personally I think this is horrible behavior. I don't think fields should ever be overridden.
I've created an isolated version that you can demo the issue here.
http://dev.davidsalazar.com/issues/safari-autofill/
Steps to replicate (ensure you use latest safari 7.0.2)
Type and user/pass click save. It should prompt you to save to keychain, accept the save.
Now click on the link load random data and you will notice that safari will now be overriding those fields with your perviously saved fields.
Workaround: create another (fake) password field and Safari is probably confused by it - autofill will be "disabled" in this case
tested in Safari 7.0.2 and 7.0.3
demo (with red fake password): http://js.pejsa.info/~jam/safari-autofill/
<form method="post" autocomplete="off">
<input type="text" name="username" id="username" value="abc" />
<input type="password" name="password" id="password" value="def" />
<input type="submit" name="submit_btn" value="Save" />
<input type="password" id="fakePassword"
style="border:0;width:10px;height:10px;background-color:red;" />
</form>
it is not possible due to new behavior in all browsers - autocomplete="off" is now ignored
for details see http://raesene.github.io/blog/2014/04/17/changing-times-the-end-of-autocomplete-equals-off/
i search this problem before day for my project. and finally i found the solution wit plug-in below.
this plug-in work structure like this. It get your input and clone it.
Use this clone and create same input properties and clone it another hidden input. After that remove your orginal input and put hidden and cloned input same position.
It's reason that. Modern browser (has keychain) control input (type password) when page loaded and mapped over DOM. After page load plug-in get input and clone and remove orginal input. this operation changes DOM mapping. So brovser cannot access this control when page redirect. So don't suggest yo to save password.
You can use this plug-in for this problem.
Notes:
If you use another plug-in like me. Forexample jquery-keyboard plug-in for password secure enter. you shoul modify your initkeyboard method. becasue keyboard control your input and init near this input. you could change this init method like below
init keyboard changing
before
var _inputwidth = $(elm).parent().find('input').width();
after
var _inputwidth = $(elm).parent().find('input[type=text],input[type=password]').width();
because plug-in output like this
<input type="hidden" id="txtPass" name="txtPass" spellcheck="false" autocomplete="off">
<input type="text" id="txtPass" name="txtPass" spellcheck="false" autocomplete="off">
If you have any keypress or keydown event initialize for this input put this codes after plug-in init. because this plug-in change DOM mapping
this plug-in usage like below
$('input[type=password]').disableAutocomplete();
this is creator desctiption
This jQuery plug-in enforces the autocomplete=off HTML attribute on
password (and other) fields. Recent browsers have chosen to ignore
this attribute in favor of user preferences. However, some financial
(and other) institutions may have good reasons to enforce this
practice.
jQouery Disable AutoComplete
Old comment
I have a page with 2 inputs. one of these input type password, other text (username password form). Safari doesn't work with autocomplete="off". I use for this problem two inline hidden input. These inputs have generic names as below. My original username password input has different name so Safari first looks for a keychain to get or set these inputs. You can use this solution to prevent Safari using a keychain for your secure page.
<input type="text" name="Username" style="display:none;"/>
<input type="password" name="Password" style="display:none;" />

Categories

Resources