tinyMCE jQuery form validation - javascript

I'm trying to use tinymce's getContent() to make a custom validation rule, how can I do this with jquery validation? I need to apply the rule to a textarea formatted with tinymce.
Validation: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
$("#element").click( function(e) {
console.log(tinyMCE.activeEditor.getContent());
$("#someForm").validate({
rules: {
title: {
required: true
}
}
});
});
I'm thinking of just using a little bit of javascript with getContent() because it looks like there's just as much effort creating a workaround to get jquery validation working with tinymce. Thoughts on possible solutions?

The following stackoverflow questions should help you on that issue:
validating multiple TinyMCE Editor
Jquery validation form with TinyMCE field who gives no error by empty value

Hi if your are not getting client side validation on form submit time when you are with tinymce try this code
suppose your have two html editor 1 is txtAboutCompanyand 2 is txtProductinfo
this is client side code
<div class="divclass">
#Html.LabelFor(model => model.txtAboutCompany, new { #class = "required" })
#Html.EditorFor(model => model.txtAboutCompany)
<span class="field-validation-error" id="AC" style="margin:9px 0 0 157px;"></span>
</div>
this is jquery
$("#BusinessProfile").click(function () {
var aboutC = $("#txtAboutCompany").val()
var pinfo = $("#txtProductinfo").val();
if (aboutC == "" && pinfo == "") {
$("#AC").append("").val("").html("Please enter about company")
$("#PI").append("").val("").html("Please enter product information")
$("#bpform").valid();
return false;
} else if (aboutC == "") {
$("#PI").append("").val("").html("")
$("#AC").append("").val("").html("Please enter about company")
$("#txtAboutCompany").focus();
$("#bpform").valid();
return false;
} else if (pinfo == "") {
$("#AC").append("").val("").html("")
$("#PI").append("").val("").html("Please enter product information")
$("#txtProductinfo").focus();
$("#bpform").valid();
return false;
}
else {
$("#AC").append("").val("").html("");
$("#PI").append("").val("").html("");
//return true;
$("#bpform").validate();
}
});
you can get your all required validation on form submit time
I know this is not proper way but you can do it .

function tinymceValidation() {
var content = tinyMCE.activeEditor.getContent();
if (content === "" || content === null) {
$("#questionValid").html("<span>Please enter question statement</span>");
} else {
$("#questionValid").html("");
}
}
tinymce.activeEditor.on('keyup', function (e) {
debugger;
tinymceValidation();
});
$(form).submit(function (e) {
tinymceValidation();
});

Related

Rails with HTML5 validation and JS

In my rails app I have validation form for matched email. For some reason validation doesn't worked - it shows error below form (when email addresses are not equal) but it submits the form and goes to the next page anyway.
validations.js
if (registrationsForm.length > 0) {
restrictZipCodeToNum();
restrictPhoneToNum();
submit.on('click', function(e) {
var invalidInput = $('input:invalid');
e.preventDefault();
if (emailField.val() !== emailConfirmationField.val() && emailField.length > 0) {
emailInvalidMsg.show();
emailField.addClass("invalid");
emailConfirmationField.addClass("invalid");
if (emailField.val() !== '') obligatoryInvalidMsg.hide();
}
validateEmail();
scrollToFirstInvalid();
if (invalidInput.length === 0 && !fileInput.hasClass('invalid')) {
form.submit();
} else {
invalidInput.addClass('invalid');
validateInput();
}
});
}
new.html.erb
<div
class="col-sm-12 col-md-12 col-xs-12 text-center bank-employees-users-registration__registrations-submit--wrapper">
<%= submit_tag t('.submit'), class: "bank-employees-users-registration__submit-btn registrations" %>
</div>
Any idea? I put the debugger below the submit.on('click', function(e) { to check what is under invalidInput but it shows correct value - input:invalid. So maybe some form is overriding the whole logic, I don't know, any suggestions are welcomed.
Function of checking if email address are the same is here:
function validateEmail() {
$('input[type="email"]').change(function() {
if (emailField.val() === emailConfirmationField.val() && emailField.val() !== '') {
obligatoryInvalidMsg.hide();
emailInvalidMsg.hide();
emailField.removeClass("invalid");
emailConfirmationField.removeClass("invalid");
} else if (emailField.val() === emailConfirmationField.val() && emailField.val() === '') {
emailInvalidMsg.hide();
obligatoryInvalidMsg.show();
emailField.addClass("invalid");
emailConfirmationField.addClass("invalid");
} else {
obligatoryInvalidMsg.hide();
emailInvalidMsg.show();
emailField.addClass("invalid");
emailConfirmationField.addClass("invalid");
}
});
}
EDIT
After debugging I think the main problem is in last if block -> if (invalidInput.length === 0 .... When I put debugger below this block and in console wrote invalidInput.length I will get 0 in case when first address in from is 123#example.com and the confirmation email address is 4321#example.com. When I have empty field it shows correctly as 1 or 2 (depends on empty field). No idea what's going wrong.
Take a look to Hemant Metalia response on this post
He mentions that's is important to use event.preventDefault() instead of e.preventDefault(), maybe it works for you.

Form Validation w/Javascript - Not working

I have the following form, done with HTML and Javascript validation.
var submitOK=true;
function validate(){
submitOK=true;
checkName();
checkSurname();
checkCourse();
checkDate();
checkEmail();
if(submitOK == false) {
return false;}
}
function checkName() {
var name = document.getElementById("name");
if(myform.name.value.length==0)
{
document.getElementById("checkname").innerHTML="Please, enter a valid name";
submitOK=false;
}
}
(COMPLETE CODE IN HERE)
http://jsfiddle.net/unkok6or/
The fields Course, Date, Name, Surname and Email have to be required. I don't know why my code is wrong and how to fix it.
-What I would like, is an error message to appear if one of the fields is not complete. Now the form runs and works even if one of them is not completed.
-The email with the correct format (without Regex).
Thanks in advance! :)
I simplified your code a little bit. This worked for me. The key thing to remember that your submit function must return a true to submit or false to stop the submit.
var submitOK=true;
function validate(){
submitOK=true;
checkName();
checkSurname();
checkCourse();
checkDate();
checkEmail();
return submitOK;
}
function checkName() {
if( document.getElementById("name").value.length==0)
{
document.getElementById("checkname").innerHTML="Please, enter a valid name";
submitOK=false;
}
}
function checkSurname() {
if(document.getElementById("surname").value.length==0)
{
document.getElementById("checksurname").innerHTML="Please, enter a valid surname";
submitOK=false;
}
}
function checkEmail() {
if(document.getElementById("email").value.length==0)
{
document.getElementById("checkemail").innerHTML="Please, enter an email";
submitOK=false;
}
}
function checkCourse() {
if(document.getElementById("course").selectedIndex < 1 ) {
document.getElementById("checkcourse").innerHTML="Please, select a course";
submitOK=false;
}
}
function checkDate() {
if(document.getElementById("date").selectedIndex < 1) {
document.getElementById("checkdate").innerHTML="Please, select a date";
submitOK=false;
}
}
You need to return true when your validation passes so change
if(submitOK == false) {
return false;}
to
return submitOk;
If you just need to make sure all the fields are filled, why don't you use required keyword on ur input types.
And for drop down you can disable the select option that way you don't need to check if the user has selected the default value.

How do I use javascript to prevent form submission because of empty fields?

How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}

JQuery Validation for Two Password Fields

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.

JQuery condition with blank input

I need to do multiple checks in a jquery condition ...
I am looking for something like this:
IF checkbox_A is Checked then
If input_A is empty then alert('input_A is Required')
else Add a class="continue" to the div below.
<button id="btn1">Continue</button>
Possible?
I normally wouldn't do this as you haven't even shown an attempt to write any code yourself, but I'm in a good mood.
if ($("#checkboxA").is(":checked")) {
if ($("#inputA").val() == "") {
alert("input_A is required");
}
else {
$("#btn1").addClass("continue");
}
}
$(document).ready(function() {
if($("#yourCheckBoxId").is(":checked")) {
if($("#yourInputId").val() == "") {
alert("empty");
}
else {
$("button[id='btn1']").addClass("continue");
}
}
});
yes, it's possible:
$('#checkBoxA').click(function() {
var checkBoxA = $('#checkBoxA');
var textBoxA = $('#textBoxA');
if (checkBoxA.checked())
{
if (textBoxA.val() == "")
{
$('#btn1').removeClass('continue');
alert("No value entered");
textBoxA.focus();
}
else {
$('#btn1').addClass('continue');
}
} else {
$('#btn1').addClass('continue');
}
});
Maybe
if ( document.getElementById('checkbox_A').checked ){
if (document.getElementById('input_A').value == ''){
alert('input_A is Required')
} else {
$('#btn1').addClass('continue;);
}
}
But if you have multiple elements you want to validate you can avoid manual checking of each field and automate by adding an required class to the element that are required..
<input type="text" name="...." class="required" />
now when you want to validate the form you do
// find the required elements that are empty
var fail = $('.required').filter(function(){return this.value == ''});
// if any exist
if (fail.length){
// get their names
var fieldnames = fail.map(function(){return this.name;}).get().join('\n');
// inform the user
alert('The fields \n\n' + fieldnames + '\n\n are required');
// focus on the first empty one so the user can fill it..
fail.first().focus();
}
Demo at http://jsfiddle.net/gaby/523wR/

Categories