JavaScript Form Validation for Textarea with Multiple Values - javascript

How would I implement error checking of multiple values entered into a textarea? I need to make sure that the values entered use commas as a delimiter before the form is submitted.

You can use
value.split(",")
to separate each word and individually validate them and
value.split(",").length < 2
to check if commas were entered. Should be good to get you started.
Update: I have update the fiddle with your new inputs. It includes check for empty inputs before or after comma, and it trims out spaces before validation
Working example here

Here is a sample implementation:
Markup
<textarea id="textarea" placeholder="comma separated values"></textarea>
<span id="msg"></span>
<br>
<button onclick="submit()">Submit</button>
Script
function isValid() {
var value = document.getElementById("textarea").value;
var values = value.split(',');
if(values.length > 0 && values.length < 5){
for(var i =0;i<values.length;i++);{
if(parseInt(values[i]) === NaN) return false;
}
return true;
}
return false;
}
function submit(){
if(isValid()){
document.getElementById("msg").innerText = "Valid";
//submit the form
} else {
document.getElementById("msg").innerText = "not a valid input";
}
}

Related

Javascript form value restriction

I am trying to create a form which will store values in an empty array but the values must be between 0 to 5 and comma separated. the problem is it alerts if values is more than 5 but still stores the value in the array. I want it to alert and then restore the form value.
Here is my code:
<form name ="form1" onsubmit="return validateForm()">
<input type="number" name="text" id="inputText" name="inputText" />
<button onclick="pushData();">Insert</button>
<p id="pText"></p>
</form>
And javascript:
function validateForm () {
var form = document.forms["form1"]["inputText"].value;
if(form <0 && form >= 6) {
alert('value should must be between 0 to 5');
return false;
}
}
// create an empty array
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for(i = 0; i < myArr.length; i++) {
pval = pval + myArr[i];
}
// display array data
document.getElementById('pText').innerHTML = "Grades: " + pval ;
}
Try
if (form <0 || form >= 6)
I think it may work better if you reorganize where the functions are being bound.
Event propagation order:
The button is clicked, and the value is pushed into the array.
The form's submit event triggers, and validates the values, but it's too late.
There are many ways to approach this one, but the simplest would be to call pushData at the end of your validateForm.
Adjusted the condition, because there's no way for a number to
be less than 0 AND greater than or equal to 6 at the same time.
Also added event.preventDefault to stop form submission.
JavaScript
function validateForm (event) {
event.preventDefault();
var form = document.forms["form1"]["inputText"].value;
if (form < 0 || form > 5) {
alert('value should must be between 0 to 5');
return false;
}
pushData();
}
HTML
<form name="form1" onsubmit="validateForm(event)">
<input type="number" id="inputText" />
<button type="submit">Insert</button>
<p id="pText"></p>
</form>
JSFiddle
Note that per the MDN:
A number input is considered valid when empty and when a single number
is entered, but is otherwise invalid.
With this particular form element you may add min and max attributes so that the user must enter a value within a specified range. Therefore, the current contents of the OP's validateForm() function are superfluous. Additionally, that function has a problematic line of code:
if(form <0 && form >= 6) {
You cannot have a value that is both less than zero and greater than or equal to six. Use instead a logical OR, i.e. "||" operator for the logic to work.
The following code allows for a user to select numeric values in the range that the OP specifies and then it displays them in a comma-separated format, as follows:
var d = document;
d.g = d.getElementById;
var pText = d.g('pText');
pText.innerHTML = "Grades: ";
var inputText = d.g("inputText");
var myArr = [];
function pushData() {
var notrailingcomma = "";
myArr.push(inputText.value);
if (myArr.length > 1) {
notrailingcomma = myArr.join(", ").trim().replace(/,$/g,"");
pText.innerHTML = "Grades: " + notrailingcomma;
}
else
{
pText.innerHTML += inputText.value;
}
}
d.forms["form1"].onsubmit = function(event) {
event.preventDefault();
pushData();
};
p {
padding: 1em;
margin:1em;
background:#eeeeff;
color: #009;
}
<form name="form1">
<input type="number" id="inputText" name="inputText" min=0 max=5 value=0>
<button type="submit">Insert</button>
</form>
<p id="pText"></p>
A couple of points with respect to the form:
The OP's HTML has an error in the input field: it has two names. I dropped the one with a name of "text".
I like what #thgaskell recommends with respect to changing "Insert" into a submit button, preventing the default action of submitting the form, and associating pushData with the form's onsubmit event. So, I've modified the code accordingly.

How to prevent characters being submitted with form input

I'm in the process of creating a gambling website, but currently with the betting form input you can type a negative number etc (-100) and you will have 100 coins put into your balance.
I need to restrict the use of anything but number digits being used within the input. Currently my work around is blocking the user from typing in anything other than numbers but you are able to hop into the developer tools and insert the value manually.
I believe i need to have an onSubmit validation for the input which says if anything but numbers are inserted do not allow the submit.
I'm not sure how i will do this, thanks for the help!
put onkeypress="return onKeyValidate(event,alpha);" on your input box,and
call the function
function onKeyValidate(e,charVal){
var keynum;
var keyChars = /[\x00\x08]/;
var validChars = new RegExp(charVal);
if(window.event)
{
keynum = e.keyCode;
}
else if(e.which)
{
keynum = e.which;
}
var keychar = String.fromCharCode(keynum);
if (!validChars.test(keychar) && !keyChars.test(keychar))
{
return false
} else{
return keychar;
}
}
Use ctype_digit()
//returns true
<?php
if (ctype_digit('123')) {
echo 'true';
} else {
echo 'false' ;
}
?>
//returns false
<?php
if (ctype_digit('-123')) {
echo 'true';
} else {
echo 'false' ;
}
?>
you can use this reguler expression to validate for numbers
samp html <button type="submit" onclick="myfunc()">Click Me!</button>
function myfunc(){
var a = /^\d*$/;
{
if(!a.test(value of input))
{
alert('Please provide a Number');
return false;
}
}
}
here
/ at both ends mark the start and end of the regex
^ and $ at the ends is to check the full string than for partial matches
d* looks for multiple occurrences of number charcters
if you want only positive numbers use this/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/
this jquery code can solve your problem
$(function(){
$("#submit").click(function(evnt){
var inptTxt = $("#myField").val();
if(check(inptTxt)){
//your test true then submits
$('#form').submit;
}else{ //test failed
evnt.preventDefault();
}
})
})
here the #submit is the id of submit button and #form is the id of the form to be submitted

How to add a validation error message next to a field using jQuery

Hi have a form with a few fields. Amongst them:
<div>
<label for="phoneNumber" class="label">Phone Number</label>
<input name="phoneNumber" type="text" id="phoneNumber" size="13" style="float:left;margin-right:10px;">
</div>
<div>
<input type="checkbox" name="activePN" id="activePN" checked >
<label for="activePN">Active</label>
</div>
The, when the form is submited, I want to validate the input and write next to each field for whichever field didn't validate. Like this:
$('#submit').click(function () {
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
if (strippedPN.length !== 10) {
$('#phoneNumber').text('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
...
...
...
});
I was hopping that adding those <p> </p> tags would do it. But they don't...
Note: I also tried with html() instead of text() and with activePN instead of phoneNumber.
Use .after().
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
It might be wise to add a class to your p tag too, so you can remove them when the number is edited to be correct.
Try:
$('#submit').click(function(){
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, ''); //strips non-digits from the string - already a String
if(strippedPN.length !== 10){
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
}
Its best to use jqueryvalidation plugin.
But in some scenario may be you need to show validation message using custom code, then below may help.
Code
var errorSeen = false;
$('#txtname').keyup(function (e) {
var validInput = false; // TODO set your validation here
if (!validInput) {
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorSeen === false && errorMessageVisible === false) {
$('#txtname').style.borderColor = "red";
$('#txtname').after("<span class='validationMessage' style='color:red;'>
Name is required.</span>");
errorSeen = true;
}
}
else {
$('#txtname').style.borderColor = "";
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorMessageVisible)
$(".validationMessage").remove();
errorSeen = false;
}
});

Need Help Validating Textbox for Specific Length and content

I have the following validation code on my .asp webpage. I also need to validate the txtndc textbox so that the data entered looks like this. 00000-0000 Currently they can enter any info in this textbox. The entry should always be 5 numbers a dash and 4 numbers. Any help would be greatly appreciated.
function form_onsubmit() {
if (form1.txtdrug.value == "")
{
alert("Drug Name Needed");
return false;
}
if (form1.txtndc.value == "")
{
alert("NDC Number Needed");
return false;
}
if (form1.txtndc.value != "" && form1.txtdrug.value != "")
{
alert("Drug was Successfully entered into the database, hit enter to continue.");
return true;
}
}
How would the syntax be written. The textbox i am trying to check is
<input type="text" name="txtndc" size="35">.
I am not sure how to enter your code below above into my page. Please Help
Using Javascript regex#test function.
x = /^[0-9]{5}-[0-9]{4}$/;
console.log(x.test("12113-1234"));
>>> x = /^[0-9]{5}-[0-9]{4}$/; console.log(x.test("00000-0004"));
true
Demo: http://jsbin.com/axikiv/1/edit

checking space between text in javascript

I want to check the gap between two or more words, i have given as an input, in a text box. If there had any space, then i want to alert user that no space is allowing. I can check the existence of text simply using "if else" statement. But can't do the desired stuff in this way. My code is given below :
<script type="text/javascript">
function checkForm()
{
var cName=document.getElementById("cName").value;
var cEmail=document.getElementById("cEmail").value;
if(cName.length<1)
{
alert("Please enter both informations");
return false;
}
if(cEmail.length<1)
{
alert("Please enter your email");
return false;
}
else
{
return true;
}
}
Name : <input type="text" id="cName" name="cName"/>
<br/>
<br/>
Email : <input type="text" id="cEmail" name="cEmail"/>
<br/>
<br/>
<input type="submit" value="Go!"/>
</form>
Thankyou
Just use the match() method of strings. For example:
'Spaces here'.match(' ');
That returns true.
'Nospace'.match(' ');
That returns false.
So for what you want, just use something like this:
if(cName.match(' ')){
alert('Spaces found!');
return false;
}
Demo
your question not very clear , but i hope you want to count your words you can use the following code to split a text and by using the length property you count the word
var b = document.getElementById("cName").value;
var temp = new Array();
temp = b.split(' ');
var count= temp.length;
and if you want to validate your name field that should not use any space
if ( ^[A-Za-z]$.test(document.getElementById("cName").value) ) {
// your code;
}
if ( document.getElementById("cName").value.indexOf(' ') > 0 ) {
alert('space found');
}

Categories

Resources