I wonder if HTML5 have any formvalidation for dual entry (write 2 identical password) and can you write own exceptions?
Thanx in advance!
If you want something a bit nicer and HTML5-utilising, try this:
http://www.html5rocks.com/en/tutorials/forms/html5forms/
<label>Password:</label>
<input type="password" id="password" name="password">
<label>Confirm Password:</label>
<input type="password" id="passwordconf" name="passwordconf" oninput="check(this)">
<script language='javascript' type='text/javascript'>
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('The two passwords must match.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
</script>
Make it fancy by adding this to your CSS (below). It puts a red border around the offending input fields when they fail HTML5 validation.
:invalid {
border: 2px solid #ff0000;
}
All done. You should still use an alert() or server-side validation to ensure that the user inputs both passwords correctly. Don't rely on client-side anything.
I had a similar problem, and to solve it using the HTML5 api I did this: setted a pattern for the password to contain at least eight letters and a number. Then to make them matching I did:
var password = document.querySelector('#password'),
passwordConfirm = document.querySelector('#password_confirm');
[].forEach.call([password, passwordConfirm], function(el) {
el.addEventListener('input', function() {
if (!el.validity.patternMismatch) {
if ( password.value === passwordConfirm.value ) {
try{password.setCustomValidity('')}catch(e){}
} else {
password.setCustomValidity("Password and password confirm doesn\'t match")
}
}
}, false)
});
where with el.validity.patternMismatch check for the pattern validity first and then check for the validity of the two.
Here is my password input with the pattern.
<input type="password" pattern="^((?=.*(\d|\W))(?=.*[a-zA-Z]).{8,})$" id="password" />
I'm quite sure that's not possible. Also, it can be easily covered by javascript so why not use that instead?
This works perfectly well:
<script language="javascript">
function checkPassword() {
if (document.pwForm.pw1.value != document.pwForm.pw2.value) {
alert ('The passwords do not match!');
return false;
}
}
</script>
<form action="filename.ext" name="pwForm" method="GET/POST">
<input type="password" name="pw1" value=""><br />
<input type="password" name="pw2" value=""><br />
<input type="Submit" name="CheckPassword" value="Check Passwords" onClick="return checkPassword();">
</form>
Thanks Kicker, that was really useful.
I extended it a little to make the password and password confirm inputs to be invalid as soon as typing in the input started.
var password = document.querySelector(' input[name=usr_password]');
var passwordConfirm = document.querySelector(' input[name=usr_password_confirm]');
if (password && passwordConfirm)
{
[].forEach.call([password, passwordConfirm], function(el) {
el.addEventListener('input', function() {
if ( el.validity.patternMismatch === false) {
if ( password.value === passwordConfirm.value ) {
try{
password.setCustomValidity('');
passwordConfirm.setCustomValidity('');
}
catch(e){}
}
else {
password.setCustomValidity("The two passwords do not match");
}
}
if ((password.checkValidity() && passwordConfirm.checkValidity()) === false)
{
password.setCustomValidity("The two passwords do not match, and they don't comply with the password rules.");
passwordConfirm.setCustomValidity("The two passwords do not match, and they don't comply with the password rules.");
}
else
{
password.setCustomValidity('');
passwordConfirm.setCustomValidity('');
}
}, false)
});
}
I think this is what you are looking for.
<p>Password: <input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" name="pwd1" onchange="
this.setCustomValidity(this.validity.patternMismatch ? 'Password must contain at least 6 characters, including UPPER/lowercase and numbers' : '');
if(this.checkValidity()) form.pwd2.pattern = this.value;
"></p>
<p>Confirm Password: <input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" name="pwd2" onchange="
this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');
"></p>
This will do the password and retype password fields validation.
Another option is to use http://jqueryvalidation.org/validate/, if you don't mind using Jquery to do your dirty work.
Check out http://jqueryvalidation.org/equalTo-method
<form id="myform">
<label for="password">Password</label>
<input id="password" name="password" />
<br/>
<label for="password_again">Again</label>
<input class="left" id="password_again" name="password_again" />
<br>
<input type="submit" value="Validate!">
</form>
<script>
$( "#myform" ).validate({
rules: {
password: "required",
password_again: {
equalTo: "#password"
}
}
});
</script>
You can also write more complicated methods if required: http://jqueryvalidation.org/category/plugin/
Related
I'm quite new to Angular, and I've already searched the web, without finding a correct solution for my situation.
I have a dynamic form created by a *ngFor. I need to disabled the submit button if the inputs are all empty and show the alert div; but I need to enable the submit if at least one of those forms contains something different from ''.
Here is my html code
<form class="form-inline" #form="ngForm">
<div class="form-group" *ngFor="let meta of state.metaById; let i = index" style="margin: 5px">
<label>{{meta.nome}}</label>
<input type="text" class="form-control" #nome (blur)="inputInArray(nome.value, i);">
</div>
<button type="button" class="btn btn-primary" (click)="getCustomUnitaDocumentaliRow(this.param)" [disabled]="fieldNotCompiled">invia</button>
</form>
<div class="alert-notification" [hidden]="!fieldNotCompiled">
<div class="alert alert-danger">
<strong>Va compilato almeno un campo.</strong>
</div>
</div>
and here is my Typescript code
inputInArray(nome: string, indice) {
if (this.state.controlloMetaId = true) {
this.state.metadatoForm[indice] = nome;
}
// this.fieldNotCompiled = false;
for (const i in this.state.metaById) {
console.log(this.state.metadatoForm);
if (isUndefined(this.state.metadatoForm[i]) || this.state.metadatoForm[i] === '') {
this.fieldNotCompiled = true && this.fieldNotCompiled;
} else {
this.fieldNotCompiled = false && this.fieldNotCompiled;
}
console.log(this.fieldNotCompiled);
}
With this code I can check the first time a user type something in one input, but it fails if it empty one of them (or all of them)
Thanks for your time
UPDATE
Check if any input got a change that is different from empty or space, just by doing:
<input ... #nome (input)="fieldNotCompiled = !nome.value.trim()" ....>
DEMO
You can set a listener to the form changes:
#ViewChild('form') myForm: NgForm;
....
ngOnInit() {
this.myForm.valueChanges.subscribe((value: any) => {
console.log("One of the inputs has changed");
});
}
I have a form, how to get the use input in the handleSubmit() method?
handleSubmit(e) {
e.preventDefault()
//how to get the user input?
}
render() {
return (
<div className="col-sm-4">
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="user"/>
<input type="text" placeholder="comments"/>
<input type="submit" hidden/>
</form>
</div>
)
}
so far, I know three solutions:
The first one, use refs, but I can see there are lots of people saying that we should avoid using it
The second one, add onChange() to each <input>, e.g.
class Example extends React.Component {
state = {
inputValue: ""
};
handleInputChanged(e) {
this.setState({
inputValue: e.target.value
});
}
render() {
return (
<div>
<input onChange={this.handleInputChanged.bind(this)} value={this.state.inputValue}>
</div>
);
}
}
this one is fine with a few inputs. But if the form has 20 input fields, then there are 20 different onChange methods?
third, use some npm module, like redux-form.
any other suggestion? Thanks
You can actually just do an onChange on the parent form like so:
onChange(e) {
switch(e.target.type) {
case 'checkbox':
this.setState({ [e.target.name]: e.target.checked });
break;
default:
this.setState({ [e.target.name]: e.target.value });
break;
}
}
// in render
<form onChange={this.onChange.bind(this)}>
<input name="foo1" />
<input name="foo2" />
<input name="foo3" />
<input name="foo4" />
<input name="foo5" />
<input name="foo6" />
<input name="foo7" />
<input name="foo8" />
</form>
There are certain libraries like https://github.com/christianalfoni/formsy-react, https://github.com/prometheusresearch/react-forms. These forms have additional functions pre written for form submitting, validations. I think using refs is a tedious and unwanted task if the form is big with the reason being that if it is controlled form you need to access the state value for controlled components which brings unnecessary complications. You can do it but it is better to use prewritten libraries.
I'm creating a Shopify website, and I'm currently working on the customer registration form. I need to make a Confirm Password field. Does anybody know how to do this in Shopify?
Just Got it working on my register page:
The two password fields:
<div id="create_password_container">
<label for="password">Your Password<em>*</em></label>
<input type="password" value="" name="customer[password]" id="create_password" {% if form.errors contains "password" %} class="error"{% endif %}>
</div>
<div id="password_confirm_container">
<label for="password_confirmation">Password Confirmation</label> <span class="password-match">PASSWORDS DO NOT MATCH</span>
<input type="password" value="" name="customer[password_confirmation]" id="password_confirm" />
</div>
Javascript:
$('form#create_customer').submit(function(e) {
if ( $('#create_password').val() === $('#password_confirm').val()) {
//alert('Password Good!!');
} else {
$('.password-match').fadeIn("slow");
e.preventDefault(); // stops our form from submitting
}
});
The CSS for the password not-matching message:
.password-match {font-size: 12px; color: #f1152f; display:none;}
When customers receive the link to their activation they are prompted for both a password and a password confirmation. Failing that - you can add an extra input (password confirmation) and then do a simple comparison with javascript. Something like:
.... <label for="password" class="login">{{ 'customer.register.password' | t }}</label>
<input type="password" value="" name="customer[password]" id="password" class="large password" size="30" />
<label for="password-confirm" class="login">{{ 'customer.register.password' | t }}</label>
<input type="password" value="" name="customer[password-confirm]" id="password-confirm" class="large password" size="30" /> ....
and then with jquery - something like
$('form').submit(function(e) {
e.preventDefault(); // stops our form from submitting
if ( $('#password').val() === $('#password-confirm').val()) {
$('form').submit();
}
});
That was done off the top of my head - so not tested. It should compare the two password strings - and if they match, allow the form to submit. Of course - you'll probably want to do stuff like show a pop up... alert or message to say your passwords don't match etc. In which case:
$('form').submit(function(e) {
e.preventDefault(); // stops our form from submitting
if ( $('#password').val() === $('#password-confirm').val()) {
$('form').submit();
} else {
// put your validation message in here - this could be showing an element... or showing an alert etc
alert("Your passwords don't match dummy!")
}
});
You could just as easily do
$( ".errorMessage" ).fadeIn( "slow", function() {
// Animation complete
$(this).hide();
});
instead of the alert - but you'd need to make sure you have a div with a class of .errorMessage that contains your error message :)
Here is my form.
<form method="post" name="frm">
<label>Name*<input type="text" name="Name" value="<?php echo $r['Name'] ?>" onblur="if(this.value.length<3) alert('Name too short');" /></label>
<label>Username*<input type="text" name="UN" value="<?php echo $r['UN'] ?>" onblur="if(this.value.length<5) alert('Username too short');" /></label>
<label>Password*<input type="password" name="PW" onblur="validation()" /></label>
<label>Confirm Password*<input type="password" name="CM" onblur="validation()" /></label>
<?php } ?>
<input type="submit" name="Submit" value="<?php if($new) echo 'Register'; else echo 'Update'; ?>" />
</form>
Without writing separate onBlur events I am trying to get all these events into a function called validation() as I have done for password and confirm-password fields. Here is my validation function:
<script language="javascript">
function validation() {
var password = document.frm.PW.value;
var password2 = document.frm.CM.value;
if (password.length < 5) {
alert ("Password too short");
}
else if (password != password2) {
alert("password mismatch");
}
}
</script>
But with this code once I have filled password, and when I am about to start inputting for confirm-password field, it alerts the message "password mismatch". How to get rid of this? And for all the form tags if I am validating and using validation() function, then in each tag do I have to call onblur=validation()?
Don't have the password validation fired on the main password change - have it fired when you alter password2 or when you click submit. :)
If you insist on checking when you update password AND password 2, I would just add a check to see if password2 had been left blank:
else if(password !== password2 && password2 !== ""){
But doing ALL your checks on submit is a much cleaner solution (and as Rake says, it would be neater still to have a span that is updated instead of an alert).
I have the following form in an Angular partial:
<form name="submit_entry_form" id="submit_entry_form" ng-submit="submit()" ng-controller="SubmitEntryFormCtrl" novalidate >
<input type="text" name="first_name" ng-model="first_name" placeholder="First Name" required/><br />
<input type="text" name="last_name" ng-model="last_name" placeholder="Last Name" required/><br />
<input type="text" name="email" ng-model="email" placeholder="Email Address" required/><br />
<input type="text" name="confirm_email" ng-model="confirm_email" placeholder="Confirm Email Address" required/><br />
<span ng-show="submit_entry_form.$invalid">Error!</span>
<input type="submit" id="submit" value="Submit" />
</form>
The trouble I'm having is with the span at the bottom that says "Error!". I want this to show ONLY if one of the inputs is both "ng-dirty" and "ng-invalid". As it is above, the error will show until the form is completely valid. The long solution would be to do something like:
<span ng-show="submit_entry_form.first_name.$dirty && submit_entry_form.first_name.$invalid || submit_entry_form.last_name.$dirty && submit_entry_form.last_name.$invalid || submit_entry_form.email.$dirty && submit_entry_form.email.$invalid || submit_entry_form.confirm_email.$dirty && submit_entry_form.confirm_email.$invalid">Error!</span>
Which is UGLY. Any better way to do this?
Method 1: Use a function on $scope set up by your controller.
So with a better understanding of your problem, you wanted to show a message if any field on your form was both $invalid and $dirty...
Add a controller method:
app.controller('MainCtrl', function($scope) {
$scope.anyDirtyAndInvalid = function (form){
for(var prop in form) {
if(form.hasOwnProperty(prop)) {
if(form[prop].$dirty && form[prop].$invalid) {
return true;
}
}
}
return false;
};
});
and in your HTML:
<span ng-show="anyDirtyAndInvalid(submit_entry_form);">Error!</span>
Here is a plunker to demo it
Now all of that said, if someone has entered data in your form, and it's not complete, the form itself is invalid. So I'm not sure this is the best usability. But it should work.
Method 2: Use a Filter! (recommended)
I now recommend a filter for this sort of thing...
The following filter does the same as the above, but it's better practice for Angular, IMO. Also a plunk.
app.filter('anyInvalidDirtyFields', function () {
return function(form) {
for(var prop in form) {
if(form.hasOwnProperty(prop)) {
if(form[prop].$invalid && form[prop].$dirty) {
return true;
}
}
}
return false;
};
});
<span ng-show="submit_entry_form | anyInvalidDirtyFields">Error!</span>