i am validating the text box value on following conditions
It should be minimum of 3 characters
It should contain only alphabets
It should contain at least one vowel
If all the conditions get matches I am enabling the submit button.
If any of the above case are not matched I am setting an error message to div named error.
Here is my code
$document.ready(function(){
$('.tbox').focus(); // cursor in text box
$(':submit').attr("disabled",true); // disable generate button
$('.tbox').focus(fucntion(){
check_the_input()
});
});
function check_the_input()
{
var value = $(this).val();
$('.tbox').bind('keyup blur',function(){
$(this).val( $(this).val().replace(/[^a-z]/g,'') ); }
if(value.length > 3)
{
if(value.indexOf('a') == -1 && value.indexOf('e') == -1 && value.indexOf('i') == -1 && value.indexOf('o') == -1 && value.indexOf('u') == -1)
{
$('#error').text("*Input must contain atleast one vowel");
$(':submit').attr("disabled",true);
}
else
{
$(':submit').attr("disabled",false);
}
}
else
{
$('#error').text("*Input should be atleast 3 characters")
$(':submit').attr("disabled",true);
}
setTimeout(check_the_input,100);
}
I am facing following issues here:
If I type input as aa99 the input changes to aa , but still the generated button is enabled.
I am not getting the error at the time I type the text. Only after pressing tab or clicking mouse outside the textbox I am getting error.
I would suggest rethinking the approach. Consider this simpler example:
HTML:
<form>
<input type="text" id="myinput"/>
<button id="submit" type="submit" disabled>Submit</button>
<p class="error"></p>
</form>
jQuery:
By using a function test and an object to store your validation filters your code becomes more obvious, more elegant and you get better performance and it's easier to maintain for example to add new filters or more inputs.
Demo: http://jsbin.com/ezatap/6/edit
var $input = $('#myinput');
var $error = $('.error');
var $submit = $('#submit');
var Filters = {
min: {
re: /.{3,}/,
error: 'Must be at least 3 characters.'
},
char: {
re: /^[a-z]+$/i,
error: 'Must be only letters.'
},
vowel: {
re: /[aeiou]/i,
error: 'Must have at least one vowel.'
}
};
function test(value, filters) {
var isValid = false;
for (var i in filters) {
isValid = filters[i].re.test(value);
$error.hide();
$submit.prop('disabled', false);
if (!isValid) {
$error.show().text(filters[i].error);
$submit.prop('disabled', true);
break;
}
}
return isValid;
}
test($input.val(), Filters);
$input.on('keyup blur', function() {
test(this.value, Filters);
});
To the first question:
else
{
$('#error').text("*Input should be atleast 3 characters")
}
=>
else
{
$('#error').text("*Input should be atleast 3 characters");
$(':submit').attr("disabled",true);
}
To the second question:
When the input is being edited, no callback will be called until the input lost its focus.
If you would like to change the style of the :submit when editing, you can setup a periodically called function that checks the input every few milliseconds. here's a simple example:
function check_the_input( )
{
//routines check the input
//...
setTimeout( check_the_input, 100 ); //call me after 0.1 second
}
$(document).ready( function( ) { check_the_input( ) } );
of course there's more work to do if you want higher efficiency.
fix several error, see this: http://jsfiddle.net/4E7vv/2/
Related
I have this sample:
link
CODE HTML:
<label for="primary_phone">Primary Phone Number<span class="star">*</span></label>
<br>
<input type="text" name="primary_phone" id="primary_phone" class="_phone required-input" value="" maxlength="10">
CODE CSS:
.invalid{
border:1px solid red !important;
}
.valid{
border:1px solid green !important;
}
CODE JS:
function phoneFormat(){
$( "._phone" ).on('blur change', function() {
text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
var testt=$(this).val().match(text);
if($(this).val()=='' || $(this).val().match(text) || $(this).val().length == 0)
{
$(this).removeClass('valid').addClass('invalid');
}
else{
$(this).removeClass('invalid').addClass('valid');
}
$(this).val(text);
});
}
$( "#primary_phone" ).blur(function() {
phoneFormat();
});
I put a script that arranges text format
for example, we can add this number :
1234567890
After calling script appears next form (what is right)
(123) 456-7890
The problem is when you want to edit my phone number ... if you want to delete the last two numbers because I put the following code maxlength="10"
I want the user can not write more than 10 characters.
How do I fulfill both requirements.
If something is not explained well I'll do an edit to this post
Thanks in advance!
Just remove all special characters when you focus in on the input box:
$("#primary_phone").on("click", function() {
var thisVal = $(this).val();
var value = thisVal.replace(/[^\/\d]/g,'');
$(this).val(value);
});
Now when you click out of the input box, your original function to format the number comes in to play :)
Working fiddle : https://jsfiddle.net/reko91/gto0qeyx/2/
I would set a higher maxlength (say 15) and bind the input to keypress.
Inside the event you can check the keyCode against a set of allowed ones and suppress the event (entry of the character) otherwise.
I would also suppress the entry of numbers if we already have 10 (with one exception: if the user selected (marked) a portion of the input and that selection contains numbers.
var alwaysAllowed = [32, 40, 41, 45]; // [" ","(",")","-"]
function keyCode(keyCode) {
if (alwaysAllowed.indexOf(keyCode) !== -1) {
return "allowed";
} else if (keyCode >= 48 && keyCode <= 57) {
// 0 - 9
return "number";
} else {
// any other character
return false;
}
}
function countNumbers(text) {
// return the number of characters [0-9] in the string "text"
var counter = 0;
for (var i = 0; i < text.length; i++) {
if (parseInt(text[i]) >= 0 && parseInt(text[i]) < 10) {
counter++;
}
}
return counter;
}
$primaryPhone.on("keypress", function () {
var keyCodeEvaluation = keyCode(event.keyCode);
if (keyCodeEvaluation === false) {
event.preventDefault();
} else if (keyCodeEvaluation === "number") {
var value = this.value,
counter = countNumbers(value.substring(this.selectionStart, this.selectionEnd));
//
if (counter === 0 && countNumbers(value) > 9) {
event.preventDefault();
}
}
});
This would allow the user to edit (or write) the phonenumber with your format applied.
MORE IMPORTANTLY
You should rewrite your phoneFormat() function.
Each execution adds another event listener. The first time you change the input value it executes one time. Then two times, three times and so forth.
You should also store objects you use repeatedly in a variable, e.g. $( this ) (creating the same jQuery object each time is a performance killer).
Here is a working example that should cover most of your use cases.
Ok, I have a form with lots of different inputs, each has the same class name on it. What I need to do is loop though all of these inputs, which the user can add more to, with an AJAX call, making sure all inputs are four numbers only.
Now I can get it to check that it is of a length but when I try to add a check to make sure its a number, it does not seem to work, this is my current code:
var ValidMyData = function() {
$('#FORM-ID-HERE').on('submit',function(e) {
e.preventDefault();
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
$(Numbers).each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 ) {
return $(this).css("background-color","#FF0004");
} else {
return $(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
This works, if the inputs on my number field are not four in length, it makes the background color red, and then removes that background color if its then changed to be four.
I have tried some things but nothing as worked. I have mainly being playing with the IsNumeric() function, by adding that on my if check. Also, although this works, I don't think my return call is working right, I think I am doing something wrong but can not put my finger on it :). - When I console.log the CheckNumbers() inner function, I get undefined back.
All help most welcome.
Thanks
this code will check if it is 4 characters and if it's a number:
var ValidMyData = function() {
$('#FORM-ID-HERE').bind('submit',function(e) {
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
Numbers.each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 || !/([0-9])+/.test(String(GetCurrentInput))) {
return $(this).css("background-color","#FF0004");
e.preventDefault();
} else {
$(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
EDIT
I updated the answer using your own code, which now will submit the form if all the inputs are filled correctly, else it highlights it and doesn't submit the form.
How is it possible to display an alert with jQuery if I click the submit button and the value of the input field is empty?
<input type="text" id="myMessage" name="shoutbox_msg" size="16" class="field_nosize" maxlength="150">
<input id="submit" type="submit" name="submit_post" class="button_nosize" value="Senden" onclick="sendMessage(); clearInput();">
$('#submit').click(function(){
if($('#myMessage').val() == ''){
alert('Input can not be left blank');
}
});
Update
If you don't want whitespace also u can remove them using jQuery.trim()
Description: Remove the whitespace from the beginning and end of a string.
$('#submit').click(function(){
if($.trim($('#myMessage').val()) == ''){
alert('Input can not be left blank');
}
});
Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).
Also you can try this, if you want to focus on same text after error.
If you wants to show this error message in a paragraph then you can use this one:
$(document).ready(function () {
$("#submit").click(function () {
if($('#selBooks').val() === '') {
$("#Paragraph_id").text("Please select a book and then proceed.").show();
$('#selBooks').focus();
return false;
}
});
});
Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});
You could create a function that checks every input in an input class like below
function validateForm() {
var anyFieldIsEmpty = jQuery(".myclass").filter(function () {
return $.trim(this.value).length === 0;
}).length > 0
if (anyFieldIsEmpty) {
alert("Fill all the necessary fields");
var empty = $(".myclass").filter(function () {
return $.trim(this.value).length === 0;
})
empty.css("border", "1px solid red");
return false;
} else {
return true;
}
}
What this does is it checks every input in 'myclass' and if empty it gives alert and colour the border of the input and user will recognize which input is not filled.
Use this instead because just trying to check if the value is not equal to an empty string won't help if there are multiple spaces.
('#submit').onclick = function(){
let count = 0;
let notEmpty = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
for(let i=0; i < $('#myMessage').value.length; i ++){
for(let j = 0; j < notEmpty.length ; j++){
if($('#myMessage').value[i]== notEmpty[j]){
count += 1;
}
}
}
if(count==0){
alert("You cannot leave this blank");
}
}
I have a textbox that looks like this
<%= Html.TextBoxFor(model => model.ContactAddress, new { autocomplete = "off", maxlength = "75" })%>
in my javascript i have this
$('.save_button_cont').click(function (e) {
var addr1 = $('#ContactAddress').val();
if(addr1.indexOf("box") > -1) {
alert("HEY NO P.O. BOXES ALLOWED ");
}
document.forms[0].submit();
});
i was hoping that this would pop up the alert before posting if the user had 'box' in the textbox. it doesnt work though.
I want to show an alert if the user enters the string 'box' in their address (the textbox).
EDIT: on the submit i am going to use a confirm box to verify that the user wants to continue. thanks for the help
Using
$("#textboxid").blur(function(){
if( $("#textboxid").val() == "box"){
alert("box typed!");
}
});
this will make your life easy!
Try this -
$('.save_button_cont').click(function (e) {
var addr1 = $('#ContactAddress').val();
if(addr1.indexOf("box") > -1) {
alert("blah");
}else {
alert('Bleh');
}
alert("TEST");
$('form').eq(0).submit();
});
You can do this:
$('.save_button_cont').click(function (e) {
var addr1 = $('#ContactAddress').val();
if (addr1.indexOf("box") > -1) alert("blah");
else alert('Bleh');
$('#formID').submit();
});
Instead of:
if(~addr1.indexOf("box")) {...} else {...}
Try
if(addr1 === "box") {...} else {...}
You could use regex to test the string for the occurrence of "box". This will allow you to do a case-insensitive search:
$('input[type="submit"]').click(function(e) {
e.preventDefault();
var input = $('#test').val();
if (/box/i.test(input)) {
alert("bad");
} else {
alert("good");
$("form").submit();
}
});
You should also put the "submit" function in your "else" statement so the form only submits on validation success.
NOTE: this could cause unwanted issues if the user happens to live on "box street".
So I need to have an input box in where people only is allowed to enter either the words "Yes" or "No". No other input is allowed. Does anybody out there knows a plugin or any other easy way to that with Jquery? I found a plugin named constraint (http://plugins.jquery.com/project/constrain), that can prevent the user from typing certain characters, but that is not enough, as the plugin can only prevent the user from typing numbers in an alphabetic field, for example. Drop down boxes or other components are not an option.
Thank you for your help.
Why not something like this (link to jsFiddle)? This will only let you type those characters that are contained in an array of allowed values? I suspect there's a better way to check for the existence of values or partial values in the array instead of looping. But this will be triggered by a user's key press, not when the control loses focus...so the UX may be better.
Hope this helps!!
HTML
Enter text: <input type="text" id="data" />
JavaScript Code
var allowedValues = ['yes','no'];
$(document).ready(function() {
$("#data").keyup(function(e) {
var typedValue = $(this).val(),
valLength = typedValue.length;
for(i=0;i<allowedValues.length;i++) {
if(typedValue.toLowerCase()===allowedValues[i].substr(0,valLength)) {
return;
}
}
$("#data").empty().val(typedValue.substr(0, valLength-1));
});
});
Based on clarification in comment, try this:
Try it out: http://jsfiddle.net/fsPgJ/2/
EDIT: Added a keypress event to deal with the user holding down a key.
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
})
.keypress(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no")
this.value = '';
})
.keyup(function() {
var val = this.value.toLowerCase();
if("yes".indexOf(val) != 0 &&
"no".indexOf(val) != 0) {
this.value = this.value.substr(0,this.value.length - 1);
}
});
Original:
If there's some reason you're not using a <select> or :radio or something, then you could have jQuery check the value on a .blur() event.
Try it out: http://jsfiddle.net/fsPgJ/
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
});
This just clears the input if the (case insensitive) value is not "yes" or "no". I also added an alert() to give the user a little feedback as to why the field was cleared. You may want a different feedback approach.