I have added a pattern attribute to my custom input field in the Shopify add to cart form.
The problem is that the pattern validator won't pass unless i refresh the page after it has caught something in the validation.
I have tried to reset the form with .reset and it works, but the custom validation messages won't work in that case.
<input required class="required" id="add-your-name-here" type="text" pattern="^[A-Za-z_]{1,15}" placeholder="{{ section.settings.text-custom-name-placeholder }}" name="properties[Ditt namn]">
var input = document.getElementById('add-your-name-here');
input.oninvalid = function(event) {
if ($(".wgcurrent").hasClass("en")) {
event.target.setCustomValidity("Letters only please");
} else if ($(".wgcurrent").hasClass("sv")) {
event.target.setCustomValidity("Vänligen ange endast bokstäver");
}
}
It works like this, except that the custom validation message won't display.
var input = document.getElementById('add-your-name-here');
input.oninvalid = function(event) {
if ($(".wgcurrent").hasClass("en")) {
document.getElementById("addtocart").reset();
event.target.setCustomValidity("Letters only please");
} else if ($(".wgcurrent").hasClass("sv")) {
document.getElementById("addtocart").reset();
event.target.setCustomValidity("Vänligen ange endast bokstäver");
}
}
I want the validation to work without having to refresh the page as it's not a very nice user experience.
You need to clear the Custom Validation message on input event. To do so use,
setCustomValidity('');
Check working code snippet below.
var input = document.getElementById('add-your-name-here');
input.oninput = function(event){
event.target.setCustomValidity('');
}
input.oninvalid = function(event) {
event.target.setCustomValidity("Letters only please");
}
<form action="#">
<input required class="required" id="add-your-name-here" type="text" pattern="^[A-Za-z_]{1,15}" placeholder="Add text here" name="properties[Ditt namn]">
<button type="submit">Submit</button>
</form>
More details on Constraints Validation at MDN
Related
Problem: I'm doing a form to be filled by the user. Once the user clicks submit, if there is an error in the form, it will show an alert. However, when the user clicks "ok" the form will reset all the fields that have been filled so the user needs to repeat in fill in the form all over again.
Question: How to fix this so that when the user clicks "ok" the data is still there?
To stop the page from re-loading add return false; after alert statement, it stops the default action from taking place from the form submit.
alert("Please fill in all mandatory fields");
return false;
You should reset form:
document.getElementById("formId").reset();
The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
Use <button type="button"> to override default submission behavior.
Use event.preventDefault() in the onSubmit event to prevent form
submission.
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('onSubmit', handleForm);
I have something that does exactly that. It's a complete working code, but I am going to give you the task of figuring out which part does what.
function submitInfo(e){
var fields = document.getElementsByClassName('input-field').length;
for(let x = 0; x < fields; x++){
var value = document.getElementById(x).value;
if(value == ''){
e.preventDefault();
var element = document.getElementById(x);
element.classList.add('no-value');
setTimeout(function(){
element.classList.remove('no-value')
},3000);
break;
}
}
}
.no-value {
border: 2px solid red;
}
<form method="post" action="">
<input type="text" name="email" placeholder="Email" class="input-field" id="0"/><br/>
<input type="password" name="password" placeholder="Password" class="input-field" id="1"/><br/>
<input type="submit" value="Submit" onclick="submitInfo(event)"/>
</form>
I hope this is what you are looking for.
i have create eway paynow button within form.
<form action="?" method="POST">
Name: <input type="text" name="customer_name" value="" />
<script src="https://secure.ewaypayments.com/scripts/eCrypt.js"
class="eway-paynow-button"
data-publicapikey="epk-6AEE4269-0010-4415-A327-8064928AEFD0"
data-amount="0"
data-currency="AUD"
data-allowedit="true"
data-resulturl="http://example.com/responseMsg.php">
</script>
</form>
i need to check whether customer_name field empty or not before load eway payment
form. if customer_name field empty don't load eway payment form.how do i do this??can i run javascript to validate this form?
The Pay Now button doesn't provide a hook to run a function before opening the payment form, nor does it use event listeners at the moment. The solution here is to:
Capture the original onclick handler
Add a new event listener which performs validation, then calls the original onclick if successful.
I've stuck to pure JS for this, jQuery would allow a cleaner implementation :-)
Also note I've removed the data-resulturl attribute and moved the URL to form tag, otherwise the window may just redirect without submitting.
<form action="http://example.com/responseMsg.php" method="POST">
Name: <input type="text" name="customer_name" value="" />
<script src="https://secure.ewaypayments.com/scripts/eCrypt.js"
class="eway-paynow-button"
data-publicapikey="epk-6AEE4269-0010-4415-A327-8064928AEFD0"
data-amount="10"
data-currency="AUD"
data-allowedit="true"
data-submitform="yes">
</script>
</form>
<script>
window.onload = function() {
// Find the eWAY Pay Now button - note getElementsByClassName is IE9+
var ewayButton = document.getElementsByClassName("eway-button")[0];
// save and remove old onclick
var oldeWAYclick = ewayButton.onclick;
ewayButton.onclick = null;
// Add new listener with validation
ewayButton.addEventListener("click", function(e){
// Stop form from submitting itself
e.preventDefault();
// Example validation
var name = document.forms[0]["customer_name"].value;
if (name == null || name == "") {
alert("Please complete all fields");
return;
}
// Display payment form
oldeWAYclick();
}, false);
};
</script>
Apply angular validations only after submit and not to show validations, if user removed text from text box after submit.
my requirement is technically,
--> if user entered text it should not show any validation
--> show validations only after if user clicked on submit
&
--> after submit if user touched that text box (or) removed text from text box then validation msgs should not show
can you guys please give me solution,
fast replies are appreciated, If you provide me fiddles then i would be very thankful.
thanks in advance
You can solve the problem by using a flag. Assume you have a form that contains an input. You have to set the flag isSubmitted to true when you clicked the submit button. and make it false when your input changes. Then show your validation message based on that flag:
Here is a hypothetical controller:
function appCtrl($scope) {
$scope.isSubmitted = false;
$scope.submit = function() {
$scope.isSubmitted = true;
//...
}
$scope.inputChanged = function() {
$scope.isSubmitted = false;
}
}
And this can be a part of your view:
<input name="inputName" type="text" ng-model="myModel" ng-change="inputChanged()" required="" />
<span ng-show="form.$error.required && form.$dirty && isSubmitted">name is required</span>
I don't know exactly what you are looking for, but I guess this piece of code could be useful.
It's just a basic form with its controller and some validated field.
Each field is required in this example, but as you can see no validation feedback is given to the user.
The validation pass only if the form is valid and then the submission is registered with a flag ( true/false ).
If the flag is true and the user touch one of the fields, all fields are blank again.
The Controller
(function(){
var Controller = function($scope){
// Parameters
var isFormSubmitted = false;
// Methods
// Shared Methods
$scope.checkFocus = function(){
if(!isFormSubmitted){
return;
}
// Reset all fields
$scope.fields = null;
// Do something
}
$scope.validate = function(){
isFormSubmitted = true;
// Do some validation
};
};
Controller.$inject = [
'$scope'
];
app.controller('MainCtrl', Controller);
})();
The view
<div ng-controller="MainCtrl">
<form name="form" ng-submit="form.$valid && validate()" novalidate>
<input ng-focus="checkFocus()" ng-model="fields.username" type="text" required placeholder="Username">
<input ng-focus="checkFocus()" ng-model="fields.password" type="password" required placeholder="Password">
<input type="submit" value="Submit">
</form>
</div>
I am using html 5 form validation for validate my form before submit, if is valid, submit, but I need validate my User Register form, so it need validate if Password Confirm value is equal camp Password, below is my form example:
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf"/><br/>
<input type="submit"/>
</form>
or in jsfiddle
How to can I create my custom validation for work like default validations?
Well you can use JQuery and attach an attribute to be selected for the passwords to validate each other via input event. Use setCustomValidity() to set the message of the input affected to override the default message when the form is submitted.
See the updated fiddle.
As you can see in the fiddle, all you have to do is add an attribute data-equal-id wherein the attribute value must be the ID of password input element to be tested.
HTML
<h1>How to create html5 validation for password confirm?</h1>
<hr>
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf" data-equal-id="pass" /><br/>
<input type="submit"/>
</form>
Javascript
$('[data-equal-id]').bind('input', function() {
var to_confirm = $(this);
var to_equal = $('#' + to_confirm.data('equalId'));
if(to_confirm.val() != to_equal.val())
this.setCustomValidity('Password must be equal');
else
this.setCustomValidity('');
});
you could try putting this code in your header:
<script>
document.getElementById('myform').onsubmit = function() {
if(!validateForm()){ // call your validation function
alert('fail!'); // remove this
return false; // prevent the form to submit
}
}
// your validation function
// compares that the passwords are equal
function validateForm(){
var pass = document.getElementById('pass').value;
var pass_conf = document.getElementById('pass_conf').value;
if(pass == pass_conf){
return true;
}else{
return false;
}
}
</script>
also put the id 'myform' to your form (or the name you want, but change it in the first line)
How about something fun like this using jQuery?
$('input[type="password"]').keyup(function() {
var pass=$('#pass').val();
var conf=$('#pass_conf').val();
if (pass == conf)
$('input[type="submit"]').removeAttr('disabled');
else
$('input[type="submit"]').attr('disabled', 'disabled');
});
The breakdown...
I am keying off of the keyup, so every time a key is pressed in the
password fields the function will fire.
I'm grabbing the value of both password fields, and comparing them.
If the values are the same, I'm enabling the submit button.
If the values are different, I'm disabling the submit button.
Pretty simple, but it works. Here is a demo: http://codepen.io/anon/pen/GxAyC/
(note - I added a couple of other visual enhancements to the demo to show what can be done)
You're using HTML5 for client-side form validation and wish to validate your form prior to form submission. Your form consists of three inputs and your only validation criteria is that both password fields match.
The most simple way to do this is to write a custom submit handler script:
const handleFormSubmit = (event) => {
event.preventDefault();
form = event.target;
if (form.pass === form.pass_conf) {
form.submit();
}
}
Above preventDefault() stops the default form submission behavior so you can execute your check. Then check if the value of the two password fields are equal. And if they are, continue form submission.
To use, attach the custom handler to your form by listening to the submit event:
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
Applied in context to example form provided:
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf"/><br/>
<input type="submit"/>
</form>
<script>
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
const handleFormSubmit = (event) => {
event.preventDefault();
form = event.target;
if (form.pass.value === form.pass_conf.value) {
form.submit();
}
}
</script>
<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)