Add validation to HTML5 required fields - javascript

I am using HTML5's required attribute on my input elements and select boxes and PHP for validation.
How can I show an alert if the required fields are not filled in? I tried using onsubmit() but the form is processed anyway and no alert is shown.

If the user's browser supports html5, he cant submit the form if not all the required fields have been written into.
Generally, you can prevent a form from submitting in jQuery like so:
$('#yourformselector').submit(function(event) {
$(this).find('[required="required"]').each(function() {
if (!$(this).val().length) {
event.preventDefault();
return false;
}
});
});

If you are using a modern/newer web browser, your default browser alerts should automatically display.
Or try:
$(document).ready(function() {
$('form').submit(function() {
var incomplete = $('form :input').filter(function() {
return $(this).val() == '';
});
//if incomplete contains any elements, the form has not been filled
if(incomplete.length) {
alert('please fill out the form');
//to prevent submission of the form
return false;
}
});
});

You may use checkValidity(), it will try to validate with attributes like pattern, min, max, required, etc. Follow this link to go deeper here
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
alert('invalid input')
} else {
alert('valid input')
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>

Related

How to check if there is no validation error exist in webpage using jquery?

I am trying to check if all form fields are filled on click a button & if valid then i am trying to add a check an alert using jquery.
jQuery("button#btn_place_order").click(function(event){
jQuery("form").validate({
submitHandler: function(form) {
alert('ok');
}
});
});
This is what i have tried but its not working, i just want to check if all fields are ok valid & filled & there is no form related error then just console or alert to check. Webpage has two or more html forms. Is their any way we can check using jquery ?
Thanks
First of you will have to prevent the default behavior of a form submit. Afterwards add a event listener to your button and check for validation of each input. (whatever that means for you). Is this what you wanted?
var el = document.getElementById("form");
el.addEventListener("submit", function(event) {
event.preventDefault();
}, true);
document.getElementById("btn").addEventListener("click", validate);
function validate(){
let valid = true;
[...document.getElementById("form").elements].forEach((input) => {
if(input.value.length == 0){
valid = false;
}
});
if(valid) alert("valid");
}
<form id="form">
<input type="text" name="TEST" id="test">
</form>
<button class="button" name="Send" value="Send" id="btn">Check</button>

How to impose a required textbox in javascript

I have a problem with my chat.
Indeed, I have a text input with the required value.
When I click on Send, it returns empty instead of stopped sending...
Can you help me please ?
<script>
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
$.post("chat-post.php", {
text: clientmsg
});
$("#usermsg").attr('required', true);
loadLog;
return false;
});
</script>
you could validate the input string like this if(clientmsg.trim()) .Better add the required=true in your html code
<input type='text' required="true">
And use with trim() they will remove the unwanted space from string
<script>
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
if(clientmsg.trim()){
$.post("chat-post.php", {
text: clientmsg
});
loadLog;
}
return false;
});
</script>
Basically you need to add a condition before sending post request if the value of that message input is empty. Please check below :
<script>
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
// This is the additional condition
if(clientmsg != '' || clientmsg != null){
$.post("chat-post.php", {
text: clientmsg
});
}
else{
alert('Please enter the message!');
}
$("#usermsg").attr('required', true);
loadLog;
return false;
});
</script>
In order for the required attribute to work, you need to have the input inside a form.
<form>
<input required type="text" />
</form>
I think there is simply no need to set the required attribute every time you click the button. You only need to do it once, so why not simply add the required attribute in the html?
Even if you don't want to add it in the HTML, just add it once.
<script>
$("#usermsg").attr('required', true); // Add the attribute required to the input
// Do the AJAX function after you submit the form.
// Before submitting, it will have to be validated, so you don't even have to validate it in JS. Just native HTML5
$("form").submit(function() {
// do the rest here
}
</script>

how to compare 2 form inputs live

I'm trying to compare two form inputs "password" and re-enter-password" to make sure there the same. I validate the password by sending it to a separate PHP that echoes back the results(which works fine)
<script type="text/javascript">
$(document).ready(function() {
$('#password_feedback').load('password-check.php').show();
$('#password_input').keyup(function() {
$.post('password-check.php', {
password: form.password.value
},
function(result) {
$('#password_feedback').html(result).show();
});
});
});
</script>
I tried sending password and re-enter=password to a PHP to compare with no luck. Can I compare the two with every keyup.
What are you checking for in your PHP script? Anything in particular that justifies the use of PHP?
You could do that only with JS, you don't need the AJAX part.
HTML :
<input type="password" id="password">
<input type="password" id="password_cf">
<div class="result"></div>
JS (jQuery) :
$('#password_cf').on('keyup', function(){
if($('#password_cf').val()== $('#password').val())
$('.result').html('They match');
else
$('.result').html('They do not match');
});
Fiddle : http://jsfiddle.net/2sapjxnu/
You can use the blur event if you want to only check once the focus is lost on that field. It's a bit less "responsive" than verifying on every key, but more performant I guess.
Not necessary jQuery, add the function:
function checkPass(input) {
if (input.value != document.getElementById('re-enter-password').value) {
input.setCustomValidity('Passwords should match.');
} else {
input.setCustomValidity('');
}
}
Add this to your re-enter-password: oninput="checkPass(this)"
OR
just call this function in the part where you want to make the comparison:
function checkPass() {
var input = document.getElementById('password');
if (input.value != document.getElementById('re-enter-password').value) {
input.setCustomValidity('Passwords should match.');
} else {
input.setCustomValidity('');
}
}
How about adding a class to each input and then:
if($(".password").val() == $(".re-enter-password").val()){
alert("it matches")
} else {
alert("no match yet");
}
Quick and dirty -
Given this markup -
<input type="password" name="pw1" />
<input type="password" name="pw2" />
You could check it client side without muliple round trips to the server using code like this -
$('[name="pw2"]').blur(function() {
var pw1 = $('[name="pw1"]').val();
var pw2 = $('[name="pw2"]').val();
if(pw2 != pw1) {
alert('passwords do not match');
}
});
Matching 2 form input fields with JavaScript by sending it off to the server to get an assertion response could render a bad user experience, because if you're doing this on each keyPress, then it generates unnecessary internet traffic - while the user is waiting.
So, instead, why not match these 2 fields directly with JavaScript?
If you are using a specific regular expression on the server for validation check as well, you can have the server put that regex "pattern" in the HTML fields - (no JavaScrpt needed for that). Then, onkeyup event you can simply do something like:
form.field2.onkeyup = function()
{
if (form.field1.value !== form.field2.value)
{
/* some code to highlight the 2 fields,
or show some message, or speech bubble */
return;
}
}
form.field1.onkeyup = form.field2.onkeyup;

Preventing resetting of form after js rejected validation

I have a survey that on button submit the first thing it runs in my js is validation if required fields are entered. Basically:
if (x == null) {
alert("You forgot to enter a required field!.");
return false;
};
Is there any way from preventing the page from refreshing/resetting what has previously been filled out if they forgot one required field?
This survey stores to local storage if that matters or can be used to help here.
You could use Jquerys .submit function (if using Jquery):
$('#formID').submit(function(){
if (x == null) {
alert("You forgot to enter a required field!.");
return false;
}
});
Handle on submit event during form submission and return false in handler method.
Check these answer first:
How to validate with Javascript an Input text with Hours and Minutes
Form Validation using JavaScript
Validate email address textbox using JavaScript
if you're not interested in using a framework like jQuery this is how it could be done:
<form name="form" onsubmit="return validate()">
function validate() {
var input_value = document.forms["form"][" .. input name .. "].value;
if( input_value == '' ) return false;
}
If you have multiple inputs, I would suggest looping through them with a foreach loop.
With jQuery it would be something like:
$( '#formID' ).on( 'submit', function() {
event.preventDefault();
// check input value
if( valid input ) $( this ).submit();
});
Interesting read: return false vs preventDefault

Displaying an image after pressing submit html

I have the following code to display an image after i press submit
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" onclick="$('#image1').show()"/>
Name is retrieved by
var y=document.forms["myForm"]["fname"].value;
Where fname is
<h4>Name: <input type="text" name="fname" size="61" /></h4>
Only problem is this is using Jquery, so I can't seem to pass it through any of my other
validations like checking if the name field is null.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
Is there a Javascript equivalent to this that I can stick in my else statement so it will only show it if the form actually submits properly passing the validation checks beforehand?
Thanks
do all that in jquery.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
else
{
$('#image1').show()
}
You should be using the .submit() event handler of jQuery instead of attaching an onclick property to the submit button. The onclick property will not fire its function in the event that a user submits the form via the enter key; however, the .submit() method will capture it as well.
$("form[name=myForm]").submit(function(e) {
//get value of name here.
var name = this.fname.value; //this refers to the form, because that is what is being submitted.
//Do validation.
if (name == null || name == "") {
//If failed, then prevent the form from submitting.
alert("First name must be filled out.");
e.preventDefault();
return;
}
//If validation passed, show image.
$("#image1").show();
});
First, remove the onclick attribute from the submit button:
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" />
Since you're using jQuery, attaching handlers to click events in JavaScript is a snap (and it's also a good practice).
I almost always use the following pattern for form validation (and on the submit of the form, rather than the click of the submit button because there are other ways to submit forms than clicking the button).
$(document).ready(function () {
var formIsValid = function formIsValid () {
// your validation routines go here
// return a single boolean for pass/fail validations
var name =document.forms.myForm.fname.value;
return !!name; // will convert falsy values (like null and '') to false and truthy values (like 'fred') to true.
};
$('form').submit(function (e) {
var allGood = formIsValid();
if (!allGood) {
e.preventDefault();
}
$('#image1').toggle(allGood); // hide if validation failed, show if passed.
return allGood; // stops propagation and prevents form submission if false.
});
});

Categories