Как валидацию приделать к textarea c wysiwyg?
Я пишу свой редактор wysiwyg, в него входит всего несколько тегов H1, H2 - загаловки
B - жирный, I - курсив, S-зачёркивание, U-подчёркивание, URL - ссылка. И мне нужно приделать валидацию jquery.validate.min.js. И я тут столкнулась с проблемой. Если использовать просто textarea, то валидация работает, но как только я убираю textarea c помощью display: none и заменяю её на iframe куда будут записываться текст и теги то уже валидация не работает. У только что созданного ifram’а есть аттрибут name frameID, на который ссылается валидация и по идеи должно выводить ошибку но ничего не выводит. В коде я использовала два примера, один с textarea, а второй c iftame. Для проверки с wysiwyg и iframe я заменяю #form-data на #wysiwyg_form вот так var v = $("#form-data").validate({, и правилах тоже надо заменить параметры text1 на frameId, вот так rules: { frameId : { requiredtext: true } } Во время проверок валидация не работает однако к форме добавляется атрибут novalidate="novalidate". Можно как-нибудь в моём случае добавить валидацию к iframe jquery.validate.min.js? Вот весь мой код: <!DOCTYPE html> <html> <head><title>Приер Editor</title> <script src="./jquery.js"></script> <script src="./jquery.validate.min.js"></script> <link rel="stylesheet" href="./bootstrap.min.css" /> <style> .has-success > .form-control { background-color: #e3ffe5; border: 1px solid #96b796; line-height: 19px; } .has-danger > .form-control { background-color: #ffebef; border: 1px solid red; line-height: 19px; } .has-danger .control-label, .has-danger .help-block, .has-danger .form-control-feedback { color: #d9534f; } #main1 { width: 400px; } </style> <script> $(document).ready(function(e){ $.validator.addMethod("requiredtext", function (value, element) { return value.length > 2; }," Заполните это поле!!!"); var v = $("#wysiwyg_form").validate({ rules: { frameId : { requiredtext: true } },errorElement: "em", errorElement: 'no', errorClass: 'form-text invalid-feedback', errorPlacement: function ( error, element ) { if ( element.prop( "type" ) === "checkbox" ) { // error.insertAfter( element.parent( "label" ) ); } else { error.insertAfter( element ); } }, highlight: function ( element, errorClass, validClass ) { $( element ).parents( ".form-group" ).addClass( "has-danger" ).removeClass( "has-success" ); }, unhighlight: function ( element, errorClass, validClass ) { $( element ).parents( ".form-group" ).addClass( "has-success" ).removeClass( "has-danger" ); }, submitHandler: function() { console.log("submit success"); } }); }); </script> </head> <body> <form id="wysiwyg_form"> <p> <div class="form-group"> <textarea id="textareaID" class="form-control" name="text1" cols="45" rows="15"></textarea> </div> </p> <p> <input type="submit" value="Отправить" /> </p> </form> <script type="text/javascript"> var doc; generate_wysiwyg("textareaID"); function generate_wysiwyg(textareaID) { document.getElementById(textareaID).style.display = 'none'; var n = textareaID; console.log(n); var type = "href"; var iframe = '<input type="button" value="H1" id="_'+textareaID+'_FormatBlock" onclick="editor_action(this.id,'+n+',1)"/><input type="button" value="H2" id="_'+textareaID+'_FormatBlock" onclick="editor_action(this.id,'+n+',2)"/><input type="button" value="B" id="_'+textareaID+'_bold" onclick="editor_action(this.id,'+n+')"/><input type="button" value="I" id="_'+textareaID+'_italic" onclick="editor_action(this.id,'+n+')" /><input type="button" value="S" id="_'+textareaID+'_Strikethrough" onclick="editor_action(this.id,'+n+')"/><input type="button" value="U" id="_'+textareaID+'_Underline" onclick="editor_action(this.id,'+n+')"/><input type="button" value="URL" id="_'+textareaID+'_CreateLink" onclick="namedlink(this.id,1)"/><br /><iframe scrolling="no" frameborder="no" src="#" id="wysiwyg'+n+'" name="frameId"></iframe>'; document.getElementById(n).insertAdjacentHTML("afterEnd", iframe); var content = "<html><head></head><body style='background-color: C0C0C0;'></body></html>"; //document.getElementById(n).value; doc = document.getElementById("wysiwyg" + n).contentWindow.document; // Write the textarea's content into the iframe doc.open(); doc.write(content); doc.close(); // Make the iframe editable in both Mozilla and IE doc.body.contentEditable = true; doc.designMode = "on"; console.log(doc); doc.addEventListener('paste',function OnEditor() { setTimeout(function() { cleanContent(); }); }, true); editor_action = function(button_id,n,num="") { var BtnParts = Array(); BtnParts = button_id.split("_"); var textareaID = button_id.replace(/^_(.*)_[^_]*$/, '$1'); var cmdID = BtnParts[ BtnParts.length-1 ]; var editor_obj = document.all["wysiwyg" + textareaID]; var editdoc = editor_obj.contentWindow.document; document.getElementById("wysiwyg" + textareaID).contentWindow.focus(); if(cmdID=="FormatBlock") { editdoc.execCommand("FormatBlock", false, "h"+num); }else if(cmdID=="bold") { editdoc.execCommand(cmdID, false, "b"); }else if(cmdID=="italic") { editdoc.execCommand(cmdID, false, "i"); }else if(cmdID=="Strikethrough") { editdoc.execCommand(cmdID, false, null); }else if(cmdID=="Underline") { editdoc.execCommand(cmdID, false, null); } } $('#wysiwyg_form').on('submit', function(event){ event.preventDefault(); document.getElementById("content").innerHTML = doc.body.innerHTML; }); } function namedlink(button_id,theType) { var BtnParts = Array(); BtnParts = button_id.split("_"); var textareaID = button_id.replace(/^_(.*)_[^_]*$/, '$1'); var editor_obj = document.all["wysiwyg" + textareaID]; var editdoc = editor_obj.contentWindow.document; var linkText = prompt("Enter the name of the link (optional):",""); // var selected = getSelectedText(editdoc); if (theType == 1) { prompt_text = "Enter the complete URL of the link:"; prompt_contents = "http://"; } linkURL = prompt(prompt_text,prompt_contents); if ((linkURL != null) && (linkURL != "")) { var theText = ''; if ((linkText != null) && (linkText != "")) { theText = "<a href="+linkURL+">"+linkText+"</a>"; } else { theText = "<a href="+linkURL+">"+linkURL+"</a>"; } console.log("wysiwyg" + textareaID); document.getElementById("wysiwyg" + textareaID).contentWindow.focus(); editdoc.execCommand('insertHtml', false, theText); } } </script> <div id="main1"> <form id="form-data" > <div class="form-group"> <textarea class="form-control" name="text1" cols="45" rows="15" id="text1"></textarea> </div> <input type="submit"> </form> </div> <div id="content"></div> </body> </html> |
Часовой пояс GMT +3, время: 23:06. |