I have a form using Tinymce, I need to check if it only contains space.
I try using this function
function validation_form()
{
var content = tinyMCE.get('main-comment').getContent().replace(' ','');
if(content == "" || content == null || content == '<p> </p>') {
return false;
}
}
But it returns true when I input several spaces and submit, I want it to return false instead.
Can anyone help me?
Thanks,
use $.trim ,
it is clean and readable.
function validation_form()
{
var content = $.trim(tinyMCE.get('main-comment').getContent({format: 'text'}));
if(content.length == 0) {
return false;
}
return true;
}
Updated: format as text, to get text content from editor. check fiddle
-- Originally wrote it in PHP --
function validation_form()
{
var content = $.trim(tinyMCE.get('main-comment').getContent());
if(content.length == 0) {
return false;
}
return true;
}
Is Correct #A.T
You can use javascript's trim method.
function validation_form()
{
var content = tinyMCE.get('main-comment').getContent().replace(' ','').trim();
if(content == "" || content == null || content == '<p> </p>') {
return false;
}
}
For more information, please check here
Solution for the same while using Angular Reactive Form Validation
Give this custom validator function in typescript file
emptyLinesValiadtor(control:FormControl):{[s:string]:boolean} | null {
let content = control.value.replaceAll(/ /gm,'')
.trim().split(" ").join("").replaceAll('<p></p>','').trim();
if(content == "" || content == null) {
return {'emptyLines': true}
}
return null;
}
In your Reactive form builder/declaration
this.formName= this.formBuilder.group({
textArea:['',this.emptyLinesValiadtor]
});
In your template form
<div
*ngIf="sForm.submitted && f.textArea.errors">
<div *ngIf="f.textArea.errors.emptyLines">
<div>Answer cannot contain empty lines/spaces</div>
</div>
</div>
where sform is reference variable and f is a typescript get method like below
get f() {
return this.formName.controls;
}
Related
<!--language:lang-html-->
<div class="form-group m-b-40 ">
<input type="text" class="form-control" id="input1">
<span class="bar"></span>
<span class="error_form" id="bname_error_message"></span>
<label for="input1">Regular Input</label>
</div>
In the above html I need to add "form-control-success" class to the input element and keep it true as long as it complies with the state if (pattern.test(bname) && bname !== '')
The same logic should also be applied to the parent element of input. But this time different class "has-success" should be added to the parent class and keep it untill it meets the same condition.
For other cases like else if(bname !== '') and (!pattern.test(bname)) the classes "form-control-success" and "has-success" that has been added to input and its parent respectively should be replaced with their opposite classes "form-control-warning" and "has-warning". This process is bind to "keyup" event. I wonder if there's a method or an elegant way that will reduce the lines of code and keep it simple.
In the clumsy way, the code looks like this:
<!--language: lang-js-->
$("#input1").keyup(function(){
check_bname();
});
function check_bname() {
var pattern = /^[a-zA-Z]*$/;
var bname = $("#input1").val();
if (pattern.test(bname) && bname !== '')
{
$("#bname_error_message").hide();
$("#input1").removeClass("form-control-warning");
$("#input1").parents(".form-group").removeClass("has-warning")
$("#input1").parents(".form-group").addClass("has-success")
$("#input1").addClass("form-control-success");
}
else if(bname === '')
{
$("#bname_error_message").html("Should not be empty");
$("#bname_error_message").show();
$("#input1").removeClass("form-control-success");
$("#input1").parents(".form-group").removeClass("has-success")
$("#input1").addClass("form-control-warning");
$("#input1").parents(".form-group").addClass("has-warning")
}
else
{
$("#bname_error_message").show();
$("#bname_error_message").html("Should contain only Characters");
$("#input1").removeClass("form-control-success");
$("#input1").parents(".form-group").removeClass("has-success")
$("#input1").addClass("form-control-warning");
$("#input1").parents(".form-group").addClass("has-warning")
}
}
here is a version of your code with some more brevity to it and using more dry coding (less repetition), however i havent been able to try the code so it may contain a bug or two, you need to try it before you run, but i hope you get general idea:
<!--language:lang-jquery-->
$elemInput.keyup(function(){
check_bname();
});
function check_bname() {
var pattern = /^[a-zA-Z]*$/,
bname = $elemInput.val(),
$elemInput = $("#input1"),
$elemError = $("#bname_error_message"),
patternMatch = pattern.test(bname) && bname !== '';
$elemError[patternMatch ? 'hide' : 'show']();
$elemError.removeClass(patternMatch ? "form-control-warning" : "form-control-success")
$elemInput.parents(".form-group").removeClass(patternMatch ? "has-warning" : "has-success")
$elemInput.addClass(patternMatch ? "form-control-success" : "form-control-warning");
$elemInput.parents(".form-group").addClass(patternMatch ? "has-success" : "has-warning")
if (!patternMatch) {
$elemError.html(bname === '' ? "Should not be empty" : "Should contain only Characters");
}
}
I think its quite good but I'd suggest some small changes:
Group your else logic in the same block because they are duplicated except the line to set the html text.
Use .parent() instead of .parents(".form-group") to get the input direct parent.
So it could look like this:
$("#input1").keyup(function(){
check_bname();
});
function check_bname() {
var pattern = /^[a-zA-Z]$/;
var bname = $("#input1").val();
if (pattern.test(bname) && bname !== '') {
$("#bname_error_message").hide();
$("#input1").removeClass("form-control-warning");
$("#input1").parent().removeClass("has-warning");
$("#input1").parent().addClass("has-success");
$("#input1").addClass("form-control-success");
} else {
$("#bname_error_message").html(bname === ''? "Should not be empty" : "Should contain only Characters");
$("#input1").removeClass("form-control-success");
$("#input1").parent().removeClass("has-success");
$("#input1").addClass("form-control-warning");
$("#input1").parent().addClass("has-warning");
}
}
$('#input1').on('keyup', function(event) {
check_bname(event.target.value);
});
function check_bname(bname) {
var $bnameInput = $("#input1");
var $bnameErrorMessage = $("#bname_error_message");
var pattern = /^[a-zA-Z]*$/;
if(bname && pattern.test(bname)) {
$("#bname_error_message").hide();
$bnameInput.removeClass("form-control-warning");
$bnameInput.parents(".form-group").removeClass("has-warning");
$bnameInput.addClass("form-control-success");
$bnameInput.parents(".form-group").addClass("has-success");
}
else {
$bnameInput.removeClass("form-control-success");
$bnameInput.parents(".form-group").removeClass("has-success");
$bnameInput.addClass("form-control-warning");
$bnameInput.parents(".form-group").addClass("has-warning");
if (!bname) {
$bnameErrorMessage.text("Should not be empty");
}
else {
$bnameErrorMessage.text("Should contain only Characters");
}
$bnameErrorMessage.show();
}
}
This code isn't doing anything when I submit the form. What am I doing wrong? In the HTML, an error message is shown or hidden based on a class.
I hope you can help me figure out this problem. Thanks in advance.
$(document).ready(function() {
function validateForm() {
var first_name = $("#first_name").value;
var last_name = $("#last_name").value;
var phone = $("#phone").value;
var email = $("#email").value;
var code = $("#vali_code").value;
var ssn = $("#ssn").value;
var income = $("#nm_income").value;
var error = $(this).find("span.error_txt").removeClass(".hidden").addClass(".show");
var emailReg = /^([w-.]+#([w-]+.)+[w-]{2,4})?$/;
if (first_name === "") {
error;
}
if (last_name === "") {
error;
}
if (email === "" || email !== emailReg) {
error;
}
if (phone === "" || phone < 9) {
error;
}
if (ssn === "" || ssn > 4) {
error;
}
if (income === "") {
error;
}
if (code === "") {
error;
}
return true;
}
});
If you call the function in inline event onsubmit you should add return keyword to the function call in your form inline event like :
<form onsubmit='return validateForm()'>
But I think the main problem comes from the .value in your code it should be replaced by .val() since the value isn't an attribute of jQuery objects.
My suggestion is to attach the submit event in the JS code like the snippet below.
NOTE: The argument passed toremoveClass() and addClass() methods shouldn't contains dot . at the start.
$(function() {
$('form').on('submit', validateForm);
})
function validateForm() {
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
$(this).find("span.error_txt").removeClass("hidden").addClass("show");
if (first_name === "") {
return false;
}
if (last_name === "") {
return false;
}
alert('Form will be submited.');
return true;
}
.hidden {
display: none;
}
.show {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id='first_name'><br>
<input id='last_name'><br>
<button>Submit</button>
<span class="error_txt hidden">Error occurred check you form fields again.</span>
</form>
You need to return false in case the form is invalid, otherwise it will be submitted.
I have following code to check if the inputs with the ids emailForm and nameForm are blank, this however isn't working when I test the form by leaving it blank.
function setInfo() {
if (document.getElementById("emailForm").value == null ||
document.getElementById("nameForm").value == null) {
alert("Please Fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
loaded();
}
}
Could someone help me with this, thanks!
Instead of checking for null specifically, you should check for falsy values. In some cases, the values for empty textboxes will be an empty string.
Replace this:
if (document.getElementById("emailForm").value == null || document.getElementById("nameForm").value == null) {
with this:
if (!document.getElementById("emailForm").value || !document.getElementById("nameForm").value) {
You shouldn't be checking whether the fields are null, you should be checking whether they content is an empty string (with .value == '').
This can be seen working in the following:
function setInfo() {
if (document.getElementById("emailForm").value == '' ||
document.getElementById("nameForm").value == '') {
console.log("Please fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
//loaded();
console.log("All sections filled in");
}
}
const button = document.getElementById('go');
button.addEventListener('click', function() {
setInfo();
});
<input id="emailForm" />
<input id="nameForm" />
<button id="go">Go</button>
Make sure you calling function setInfo()
function setInfo() {
// You can check Value.Length also or
if (document.getElementById("emailForm").value === "" ||
document.getElementById("nameForm").value === "") {
alert("Please Fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
loaded();
}
}
Try below solution:
function setInfo() {
var email=document.getElementById("emailForm").value;
var name=document.getElementById("nameForm").value;
if (email=='' || email==null || name=='' || name== null ) { // OR if (!email || !name)
alert("Please Fill in all sections");
return;
} else {
loaded();
}
}
You should check whether the string is empty or not instead of null. Try using the code below:
function setInfo() {
var a=document.getElementById("emailForm").value;
var b=document.getElementById("nameForm").value;
if (a == "" ||
b == "") {
alert("Please Fill in all sections");
} else {
email =
document.getElementById("emailForm").value;
name =
document.getElementById("nameForm").value;
alert("success alert");
}
}
i used to use jquery validation plugin but because of lack of this plugin with wysiwyg plugins i wrote a simple script to validate my form
i tried to do it like this
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article body</li>');
return false;
}
if ($('#ArticleTitle').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article title</li>');
return false;
}
$('#errors').hide();
return true ;
}
i found to 1 problem when it validate the form it's validating it field by field so the errors messages doesn't appear at once
i tried to do something like
var errors = [];
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
errors.push('<li>please enter your article body</li>');
var invalid = 1 ;
return false;
}
if ($('#ArticleTitle').val() == 0) {
errors.push('<li>please enter your article title</li>');
var invalid = 1 ;
return false;
}
if(invalid == 1){
$.each(errors , function(i, val) {
$('#errors').append(errors [i]);
});
}
$('#errors').hide();
return true ;
}
i tried to push errors as array elements and loop through them in case of invalid is true
bu this one doesn't work at it all ?
is there any way to make it work ?
if ($('#editor').val() == 0) // This is checking if value is 0
This does not make sense..
Try
if ($('#editor').val() == '') //Instead check for empty string
EDIT
Also you seem to be hiding the error's div in the end.
$('#errors').hide();
Try this code Instead
$('#validate').on('click', function() {
var errors = [];
var html = '<ul>' ;
valid = true;
$('#errors').empty();
if ($('#editor').val() == '') {
errors.push('<li>please enter your article body</li>');
valid = false;
}
if ($('#ArticleTitle').val() == '') {
errors.push('<li>please enter your article title</li>');
valid = false;
}
if (!valid) {
html += errors.join('') + '</ul>'
$('#errors').append(html);
}
else{
$('#errors').hide();
}
return valid;
});
DEMO
Two entered passwords should be the same, and I want to display a notification when they're not matching. The target is to display the notification during typing and not after pressing the save Button.
I am new to javascript and I have also tried the functionname function() notation.
following js:
function updateError (error) {
if (error == true) {
$(".error").hide(500);
}else{
$(".error").show(500);
}
};
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return true;
}
return false;
};
document.ready(function(){
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
});
and HTML:
#Html.Password("password")
#Html.Password("password-check")
<span class="error">Errortext</span> </td></tr>
but it doesn't works..
Thx!
Edit:
Now i've changed the JS code to:
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
--> now it works, but only once, after the user typed a matching password, validation stops working
Solved, problem was Quoting:
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
You are doing opposite
if (error == true) {
$(".error").show(500);
}else{
$(".error").hide(500);
}
Edit as per comment :
Try placing name within quotes like
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
In the checkSame, you may want to use indexOf to check if passwordVal contains checkVal since when typing, the password is not equal yet.
if (passwordVal.indexOf(checkVal)>-1 || checkVal.indexOf(passwordVal)>-1 ) {
return true;
}
As int2000 said, fire the checkSame on keyup seems weird, but if it's what you want, OK.
Try to change your checkSame function as follows:
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return false;
}
return true;
};
Remember that you're passing the result of checkSame to updateError, so if the passwords are the same you have no error.