JavaScript/jQuery validation for text box - javascript

I have a texbox that is like this:
<input type="text" size="30" name="form[id]" id="form_id">
I need a JavaScript function that will validate:
No Spaces allowed.
Only numbers, letters, dashes(-) and underscores(_) allowed and no other special character allowed.
Shouldn't be empty
On Submit when the user's input is violating a validation. An alert message should be displayed.

With jQuery I'll do something like that :
$('#formId').submit(function(e) {
var validator = new RegExp(/^[\w_-]{1,}$/), //Min 1 char or more
text = $('input[name="form[id]"]').val();
if(validator.test(text))
$(this).submit();
else {
alert('Code not valid');
return false;
}
});
Regular Expressions Cheat Sheet
NB : jsfiddle is down atm, code hasn't been tested

Here is the javascript
<script type="text/javascript">
function NoSpecialChars(){
var element=document.getElementById('form_id');
var specialchars= "!##$%^&*()+=[]\\\';,./{}|\":<>?";
if(element.value.length==0){
alert('Enter some text');
return false;
}
for (var i = 0; i < element.value.length; i++) {
if (specialchars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
alert ("Those are not allowed.");
return false;
}
}
return true;
}
</script>
You need to subscribe the onclientclick event of the textbox.
<input type="text" size="30" name="form[id]" id="form_id" onclientclick="return NoSpecialChars();">
Hope it helps

Use JQuery Validation Engine for Validating the Form..
Here is the Link for JQuery Validation

Related

How can I make a pop up window (alertbox) if the input isn't valid? [duplicate]

This question already has answers here:
A simple jQuery form validation script [closed]
(2 answers)
Closed 5 years ago.
Basically what i'm trying to do is that when i hit a button, it will check if something has been written, if it hasn't I would like an alert box to appear. Is this possible? Down below is what I have so far, any tips? (#inputvalue is the id of the values when writing. I created a new function for the process called validateForm. Is this possible to do in Jquery? I supose that what I wrote is more Javascript, because that's mostly what i'm used to...). //Nathalie!
function validateForm() {
var x = document.forms["#inputValue"].value;
if ("#inputValue" == "") {
alert("Name must be filled out");
return false;
}
}
Provided that you use jQuery (as you have tagged your question) you could try something like this:
$(function(){
function validateForm(){
var ele = $("#inputValue");
if(!ele.val()){
alert("Name must be filled out")
}
}
$("#btnId").on("click", validateForm);
});
$(function(){
function validateForm(){
var ele = $("#inputValue");
if(!ele.val()){
alert("Name must be filled out")
}
}
$("#btnId").on("click", validateForm);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputValue"/>
<input type="button" id="btnId" value="submit"/>
Sure, using the code you provided, you just need to target #inputValue properly and use that value in your test.
function validateForm() {
var x = document.getElementById('inputValue').value;
if (x.trim() == "") {
alert("Name must be filled out");
return false;
}
}
<form onsubmit="validateForm()">
<input id="inputValue" type="text">
<input type="submit">
</form>
Using jquery, it's basically the same thing. Here's an example using a submit handler in jquery instead of an onsubmit attribute in html, and using jquery selectors.
$('form').on('submit',function(e) {
var x = $('#inputValue').val();
if (x.trim() == "") {
alert("Name must be filled out");
return false;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="inputValue" type="text">
<input type="submit">
</form>
In addition to what Michael Coker said, it would be better if you attach an event listener by script to the form tag:
document.addEventListener("DOMContentLoaded", function() {
document.getElementsByName("form")[0].addEventListener("submit", function() {
var value = document.getElementById("inputValue").value;
if (value == "")
{
window.alert("Name must be filled out!");
}
});
});
Here is a solution using jQuery. Unlike some of the answers above, I did not use a form.
//Listen for the click of the button
$(document).on("click", "#enterButton", function(e) {
//Get the value of the input box
var F_Name = $('[name="FirstNameInput"]').val();
//If it is empty, alert.
if (!F_Name.trim()) {
alert('Empty');
}else{
//DO SOMETHING WITH THE INPUT, AJAX?
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="FirstNameInput">
<button type="button" id='enterButton'>Enter</button>

validation using javascript in visual studio on an aspx page

The email id is entered into a textbox and the validation for email is applied but there seems to be an error that the whole function is probably not called during execution
<head runat="server">
<title></title>
<script type="text/javascript">
function IsValidUrl()
{
var emailbox = document.getElementById('<%=TextBox4.Text %>');<!--textbox4 is used to receive the email entered by the user-->
var email = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (textbox.value.length > 0)<!--the email field should be non empty-->
{
if (email.test(emailbox.value))
{
return true;
}
else
{
alert("Please enter valid Email");<!--incase of an invalid email-->
return false;
}
}
else
{
alert("please enter text");
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" style="margin-left: 340px" Text="Submit" Width="96px" OnClick="Button1_Click1" OnClientClick="javascript:IsValidUrl();"/>
</form>
</body>``
There seems couple of issue with the javascript's IsValidURL function so please replace it with below code.
function IsValidUrl()
{
var emailbox = document.getElementById('<%=TextBox4.ID %>');
var email = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (emailbox.value.length > 0)
{
if (email.test(emailbox.value))
{
return true;
}
else
{
alert("Please enter valid Email");
return false;
}
}
else
{
alert("please enter text");
return false;
}
}
There are mainly two problems
<%=TextBox4.Text %> here you want id of the textBox but you are fetching value of the textBox.
textbox.value.length you want to check value of the TextBox4 but its variable name is emailbox, not textbox.
So I have just corrected those.
Hope this helps you.
Probably your function is working correctly but the page gets submitted even after the validation so replace below:
OnClientClick="javascript:IsValidUrl();"
with
OnClientClick="return javascript:IsValidUrl();"
Edit
Just figured an error in your JS code if (textbox.value.length > 0) line should be if (emailbox.value.length > 0) so try with replace it.
Another issue I found in document.getElementById('<%=TextBox4.Text %>') which should be document.getElementById('<%=TextBox4.ID %>') and in case of using master pages it should be document.getElementById('<%=TextBox4.ClientID %>') so try replacing it too.
Hope this will help !!

function not working in jsp page?

<script>
function KeepCount() {
var x=0;
var count=0;
var x;
for(x=0; x<document.QuestionGenerate.elements["questions"].length; x++){
if(document.QuestionGenerate.elements["questions"][x].checked==true || document.QuestionGenerate.elements["option"][x].checked==true || document.QuestionGenerate.elements["Description"][x].checked==true || document.QuestionGenerate.elements["fillups"][x].checked==true){
count= count+1;
document.getElementsByName("t1")[0].value=count;
}
else
{
document.getElementsByName("t1")[0].value=count;
//var vn=$('#t1').val();
// alert(vn);
//alert(vn);
//alert("value is"+count);
}
}
// var cc = document.getElementsByName("t1")[0].value;
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
}
</script>
<form action="SelectedQuestions.jsp" method="post" name="QuestionGenerate">
<input type="text" name="t1" id="t1" value="">
<input type="submit" id="fi" name="s" value="Finish" onclick="return KeepCount();">
</form>
I use the above code for checking how many check box are checked in my form my form having many check box. and if no check box are selected means it shows some message and than submit the form but for loop is working good and textbox get the value after the for loop the bellow code doesn't work even alert() is not working
**
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
This code is not working why?
**
I change my KeepCount() function code shown in bellow that solve my problem
function KeepCount()
{
var check=$("input:checkbox:checked").length;
alert(check);
if(check==0)
{
alert("You must choose at least 1");
}
return false;
}
The bug is : document.QuestionGenerate.elements["questions"] it is undefined that's why the code is not even going inside for loop use instead :
document.QuestionGenerate.elements.length

Form Validation not working on all fields but only the first

When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.

javascript return true not working

i have used the following code for javascript validation, that return true or false depending on the condition
javascript block
function fnval()
{
if(document.field.value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
Here is my HTML:
<Input type=submit name="sub" onClick="return fnval()">
Thus the js block checks if the field value is entered or not. If not it throws an alert message and return false, and hence the form does not get submitted.
But in case the value is not empty it returns a true, and still the form does not get submitted.
I have seen some queries asked by people where return false results in submission of the form. But this is exactly opposite.. and am not able to find a solution as of now.
Can anyone please help me on this?
Try getElementsByName:
function fnval()
{
if(document.getElementsByName('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
getElementsByName doesn't have IE support though. Perhaps:
function fnval()
{
if(findInput('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
function findInput(name) {
var elements = document.getElementsByTagName('input'),
length = elements.length,
i = 0,
results = [];
for(i; i<length; i++) {
if (elements[i].name === name) {
results.push(elements[i]);
}
}
return results;
}
You need to add the form name and the form value. Something like:
if ( document.formName.fieldName.value == "" )
For instance, with this kind of HTML:
<form method="post" onsubmit="">
Password: <input name="password" type="text" /><br />
</form>
The js:
if (document.form.password.value == "") {
//empty
}
i suggest using onsubmit in the form, <form ... onsubmit="return fnval()">,
try adding that and placing return false at the base of your function.
no matter what you do in js. but if you have filled action tag of form element element , the form will submit.
Syntax error:
type="submit"
not
type=submit

Categories